Title: Advanced Functions
1Advanced Functions
2Initializing Objects
- Member variables can be initialized in the body
of the constructor - or at initialization
CatCat() itsAge 5 itsWeight 8.3
CatCat() itsAge(5), itsWeight(8.3)
3Initializing Objects
- Member variables can be initialized in the body
of the constructor - or at initialization
CatCat(int age, float weight) itsAge
age itsWeight weight
CatCat(int age, float weight) itsAge(age), itsW
eight(weight)
4The Copy Constructorand Allocated Memory
- The copy constructor is called when a copy of an
object is made - When an object is passed by value into a function
- When an object is returned by value from a
function - The default copy constructor will copy pointers,
but not allocated memory
5The Copy Constructorand Allocated Memory
- The pointers in the old and new object will both
point to the same allocated memory. - If the old object is destroyed, the allocated
memory will be deleted, and the pointers in the
new object will be invalid.
6Copying Objects With Allocated Memory
class Cat public Cat() Cat(const Cat
) Cat() int GetAge() const return
itsAge private int itsAge CatCat(
) itsAge new int itsAge
5 CatCat(const Cat rhs) itsAge new
int itsAge rhs.GetAge() CatCat()
delete itsAge itsAge NULL
7The Assignment Operator
- The compiler provides a default assignment
operator operator ( ) - Cat Boots Frisky
- in addition to the constructor, copy
constructor, and destructor - Like the copy constructor, the assignment
operator must be modified for objects which have
allocated memory
8Operator Overloading
- Almost all C operators can be overloaded
- , --, , , /, ,
- This permits the operators to act on user defined
types (classes)
9Overloading
class Cat public Cat operator () //
prefix Cat operator (int) // postfix
private int itsAge float
itsWeight Cat Catoperator ( ) //
prefix itsAge itsWeight .2 return
this
10Overloading
class Cat public Cat operator () //
prefix Cat operator (int) // postfix
private int itsAge float
itsWeight Cat Catoperator (int) //
postfix Cat temp this itsAge itsWeig
ht .2 return temp
11Overloading
class Cat public Cat operator (const Cat
) private int itsAge float
itsWeight Cat Catoperator (const Cat
rhs) Cat temp this temp.itsAge
rhs.GetAge() temp.itsWeight
rhs.GetWeight() return temp
12this
- Every class member function has a hidden
parameter the this pointer - this points to the individual object