0% found this document useful (0 votes)
55 views

Class Composition: A Shape "Has A" Fixed Point

The document describes a Point class with constructors, destructors, and member functions to get and set the x and y coordinates. It also discusses class interfaces being separated from implementations, and the use of private and public members to control access to class variables and functions. Objects of a class type can be declared, and member functions defined outside the class are used to access and manipulate the private member variables of an object.

Uploaded by

sudinavada2009
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views

Class Composition: A Shape "Has A" Fixed Point

The document describes a Point class with constructors, destructors, and member functions to get and set the x and y coordinates. It also discusses class interfaces being separated from implementations, and the use of private and public members to control access to class variables and functions. Objects of a class type can be declared, and member functions defined outside the class are used to access and manipulate the private member variables of an object.

Uploaded by

sudinavada2009
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 32

Class Composition

A shape “has a” fixed point.


class Point
{
public:
Point();
Point(int, int);
~Point();
int getXCoord();
int getYCoord();
void setXCoord(int)
void setYCoord(int);
protected:
int xCoord, yCoord;
};
• Constructors
– A constructor is a special method that describes how an instance of
the class (called object) is constructed
– C++ provides a default constructor for each class, which is a
constructor with no parameters. But, one can define multiple
constructors for the same class, and may even redefine the default
constructor
– Whenever an instance of the class is created, its constructor is
called.
– A copy constructor is a special constructor that is required to
construct a new object, initialized to a copy of the same type of
object. For example,

IntCell( const IntCel & rhs ) : storedValue( rhs.storedValue)


{ } //This constructor uses an initializer list to initialize
//the data member(s) directly.
• Destructors
– A destructor is called when an object is deleted either implicitly, or
explicitly (using the delete operation)
– C++ provides a default destructor for each class, but one can
redefine the destructor of a class.
– A C++ class can have only one destructor.
Interface and Implementation
• In C++ it is more common to separate the class interface
from its implementation.
• The interface lists the class and its members (data and
functions).
• The implementation provides implementations of the
functions.
Introduction to Classes
A C++ class is used to create objects defined by the
programmer, consisting of variables and functions
Define the class Rectangle:
Tell the compiler what the class is made of
class Rectangle
Access specifiers {
private:
float width; 3 member
Not accessible
float length; variables
outside the class
float area;
public:
void setData ( float, float );
Accessible void calcArea ( );
float getWidth ( ); 5 member functions
outside the class
float getLength ( ); Prototypes used for
float getArea ( ); manipulating member
}; variables
Defining Member Functions
Definitions of member functions are written outside the
class declaration Scope resolution operator
void Rectangle :: setData ( float w, float l )
Return type
{ Member function name
Name of class width = w;
Initializing private
length = l; member variables
}
void Rectangle :: calcArea ( )
Member functions { Initializing private
can access area = width * length; member variable
member variables }
within the class float Rectangle :: getWidth ( )
{
return width; Accessing the value
of a member variable
}
float Rectangle :: getLength ( )
{
return length; Accessing the value
of a member variable 6
}
An Instance of a Class
After a class is defined, objects of the class can be
declared
Declare box an object Defines the class
Class name
of class Rectangle
Rectangle box; class Rectangle
{
Initialize member variables private:
width and length of box float width;
box.setData ( 10.0, 12.5 ); float length;
float area;
Calling object
Member function public:
void setData ( float, float );
box.calcArea ( ); void calcArea ( );
Calculates area member float getWidth ( );
variable of box float getLength ( );
cout << box.getWidth( ); float getArea ( );
};
Displays width member
variable of box
Why Have Private Members?

In object-oriented programming:
• An object should protect its important data by
making it private
• An object should provide a public interface to
access the private data

Objects usually have some variables and functions that are only
used internally and should not be modified from outside the class

If a member variable is declared as private, an


application must use a public member function to:
• Store values in the private member variable
• Retrieve values from the private member variable
Separate Specification and Implementation
Class declarations are stored in their own header file
called the class specification file
Name of header file Class specification file
rectangle.h for Rectangle class
Use an identifier
similar to class name Extension
Member functions definitions are stored in a separate
.cpp file called the class implementation file
Name of Class implementation
implementation file rectangle.cpp file for Rectangle class
Extension
An application that uses the class should #include the
specification file and link the implementation file with
the main program
UNIX command line compile
g++ appProg.cpp rectangle.cpp
Application file Implementation file
Separate Specification and Implementation
Specification file: class Rectangle
rectangle.h {
private:
#include “rectangle.h” float width;
void Rectangle :: setData ( float w, float l ). . .
{ public:
width = w; void setData ( float, float );
length = l; . . .
} float getArea ( );
. . . };
void Rectangle :: getArea ( )
{ #include “rectangle.h”
return area; void main ( )
} {
Rectangle box;
Implementation file: box.setData ( 10.0, 12.5 );
rectangle.cpp . . .
Application program: cout << box.getArea ( );
appProg.cpp . . .
Private Member Functions
Private member functions can be called from member
functions of the same class
Sometimes member functions are necessary for internal
processing but not useful to outside programs

class Rectangle void Rectangle :: setData (float w, float l )


{ {
private: Set values of private
width = w; member variables
float width; length = l;
float length; Calling a private member
calcArea ( ); function to initialize
float area; } member variable area
void calcArea ( );
public: Private member function
void setData ( float, float ); called from setData
float getWidth ( );
float getLength ( );
float getArea ( );
};
Class IntCell IntCell::IntCell( int initialValue )
{ : storedValue ( initialValue ) { }
public:
explicit IntCell( int initialValue = 0 ); Int IntCell::read( ) const
int read( ) const; { return storedValue; }
void write( int x );
private: Void IntCell::write( )
int storedValue; { storedValue = x; }
}
IntCell.h IntCell.cpp

The interface is typically placed in a file that ends with .h. The
member functions are defined as:
ReturnType FunctionName(parameterList);
The implementation file typically ends with .cpp, .cc, or .C. The
member functions are defined as follows:
ReturnType ClassName::FunctionName(parameterList)
{ …… } Scoping operator
Abstract Data Type with a Class
class Time {
public:
Time(); // constructor
void setTime(int, int, int);
void printMilitary();
void printStandard();
private:
int hour;
int minute;
int second;
};
Declaration of Objects of Type
"Time"

Time sunset, // object of type Time


arrayOfTimes[5], // array of Time obj
*ptrToTime, // pointer to Time obj
&dinnerTime = sunset; // reference
What is an Object?
• Object is a variable,
• Object is a function?
• Object is data and functions
• Object is an abstraction of something that
has attributes (property) and operations
(function calls).
Member Functions

• Member functions of Time are defined outside the


class with :: binary scope resolution operator.
• E.g.,
void Time::setTime(int h, int m, int s)
{
hour = ( h>= 0 && h < 24) ? H : 0;
...
}
Class Example Fig.6.3
• Class definition
• Member function definition
• Main program

C.f. Fig. 6.3.


Class Scope

• Class data members and member functions belong


to that class's scope.
• Within a class's scope, class members are
references by name.
• Outside a class's scope, class members are
referenced through one of the handles on an
object.
Separating interface from
implementations
• Header files contains class declarations only
• Class function definition in source file
• Driver program in another file
Public and Private Data or
Function
• Public data or functions are accessible from
outside
• Private data or functions are not directly
accessible by the user outside the class
scope
• Public functions are used as an interface to
access or modify private data
Initializing Class Objects with
Constructors
• A constructor is a class member function
with the same name as the class.
• The constructor is called whenever an
object of that class is created.
• The constructor does not return a value (not
even void).
Destructors
• The name of the destructor for a class is the
tilde (~) character followed by the class
name.
• Destructor is called when an object is going
to disappear (out of scope).
Constructors
A constructor is a member function automatically called
when a class object is created
Constructors have the same name as the class and are
generally used for initialization purposes
class Demo Program output:
{
public: Prototype In the constructor
Demo ( ); Default In main
No return }; constructor
type Demo :: Demo ( ) Definition of constructor
Class name { Class name
cout << “In the constructor\n”;
} A default constructor
has no arguments
void main ( )
{ Constructor is executed here
Demo demoObj; when object is declared
cout << “In main\n”;
}
Constructors
This constructor dynamically allocates memory for the desc array

void main ( ) Constructor is executed


{ Memory allocated
InvItem stock;
class InvItem stock.setInfo ( “Hammer”, 20 );
{ cout << stock.getDesc( ) << endl;
private: cout << stock.getUnits ( ) << endl;
char *desc; }
int units;
public: Inline default constructor
InvItem ( ) { desc = new char [51]; }
void setInfo ( char *dscr, int un )
Program output:
Inline member { strcpy ( desc, dscr );
functions units = un; } Hammer
char *getDesc ( ) { return desc; } 20
int getUnits ( ) { return units; }
};
Destructors
A destructor is a member function automatically called
when an object is destroyed
Destructors have the same name as the class and are
preceded by a tilde character ( ~ )
class Demo
{ void main ( ) Constructor
public: { executed
Demo ( ); Constructor
Demo demoObj;
Prototype for
~Demo ( ); Destructor cout << “In main\n”;
Destructor
}; } Destructor
Demo :: Demo ( ) executed
{
cout << “In the constructor\n”; Program output:
}
No In the constructor
Demo :: ~Demo ( ) Definition for
return destructor In main
{ Class name
type In the destructor
cout << “In the destructor\n”;
}
Destructors
The constructor dynamically allocates memory
The destructor frees allocated memory
void main ( ) Constructor is executed
{ Memory allocated
class InvItem
InvItem stock;
{
stock.setInfo ( “Hammer”, 20 );
private:
cout << stock.getDesc( ) << endl;
char *desc;
cout << stock.getUnits ( ) << endl;
int units;
} Destructor is executed
public:
Memory freed
InvItem ( ) { desc = new char [51]; }
~InvItem ( ) { delete [ ] desc; } Inline default destructor
void setInfo ( char *dscr, int un ) Program output:
Inline member { strcpy ( desc, dscr );
functions units = un; } Hammer
char *getDesc ( ) { return desc; } 20
int getUnits ( ) { return units; }
};
Constructors Accept Arguments
Initialization information can be passed as arguments
to an object’s constructor
class Sale Program output:
{
private: $132.50
float taxRate;
float total;
public: Parameter Inline constructor
Sale ( float rate ) { taxRate = rate; } Member variable taxRate
void calcSale ( float cost ) is initialized to value of
{ total = cost + ( cost * taxRate ); } parameter rate
float getTotal ( ) { return total; }
};
void main ( ) Declares cashier as object of class Sale,
{ executes constructor which initializes taxRate
Sale cashier ( 0.06 ); Multiplies by taxRate, assigns result
cashier. calcSale ( 125.00 ); to member variable total
cout << ‘$’ << cashier.getTotal( ); Displays value of
} member variable total 27
Overloaded Constructors
More than one constructor can be defined for a class
A function name is overloaded when multiple functions with the
same name exist
void main ( ) Uses constructor with
{ character pointer argument
class InvItem InvItem item1 ( “Hammer” );
{ InvItem item2; Uses default constructor
private: item1.setUnits ( 15 );
char *desc; item2.setInfo ( “Pliers”, 25 );
int units; }
public:
Default constructor with one default argument
InvItem ( int size = 51 ) { desc = new char [ size ]; }
Same function name Constructor with a character pointer argument
InvItem ( char *d ) { desc = new char [ strlen(d) + 1 ];
Different parameter lists strcpy( desc, d ); }
void setInfo ( char *dscr, int un ) { strcpy ( desc, dscr );
units = un; }
void setUnits ( int u ) { units = u; }
. . . .
TO SUM UP
Constructors
• All constructors have a method name that is the same as
the name of the class.
• Executed whenever an instance of the object is created.
• If constructor not declared , C++ will create one for you.
• You can have multiple constructors with different
signatures (arguments).
• Constructors can take arguments but do not have a return
type.
• They are used to set initial values of data members.
• Has to be public.
TO SUM UP
Destructors
• Destructors start with a squiggle ‘~’ and end with
the name of the class.
• A destructor is automatically called when the
object is destroy by either leaving scope or being
deleted .
• You can only have one destructor.
• If you do not declare a destructor, C++ will
provide one for you.
• Destructors can neither take values nor return
values.
• Has to be public.
TO SUM UP
Using destructors (Cont’d)
• Destructors are used for clean up work.
• They can be used to:
– release control of any resource
– release any dynamic memory

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy