Friend this-new&delete

Preview:

DESCRIPTION

c++

Citation preview

1

Week 9-10Outline• Constructors• Destructors• Friend functions• This pointer• Dynamic Memory allocation with NEW and DELETE operators

2

Constructors• Constructor function

– Special member function• Initializes data members• Same name as class

– Called when object instantiated– Executed automatically whenever an object is

created– No return type

An example of constructor• 1 // counter.cpp• 2 // An example of a constructor• 3 #include <iostream.h>• 4 • 5• 6• 7 • 8 class test• 9 {• 10 public:• 11 test() { cout << “I am constructor” <<endl; } // constructor• 12• 13 };• 14 int main()• 15 {• 16 test a,b,c; //define and initialize• 17• 18 return 0; // indicates successful termination• 19 • 20 } // end main

• In the above program, when the three objects a,b and c are created, each time an object is created, the constructor function is automatically executed and prints “i am constructor” three times

I am constructor

I am constructor

I am constructor

Another example of constructor• 1 // counter.cpp• 2 // An example of a constructor• 3 #include <iostream> • 4• 5• 6 • 7 class Counter• 8 {• 9 private:• 10 unsigned int count; // count• 11 public:• 12 Counter() { count=0; } // constructor• 13 void inc_count() { count++; } // increment count• 14 int get_oount() { return count; } // return count• 15 };• 16 int main()• 17 {• 18 Counter c1,c2; //define and initialize• 19 cout <<“\nc1= “ <<c1.get_count(); //display• 20 cout <<“\nc2= “ <<c2.get_count();• 21 c1.inc_count(); //increment c1• 22 c2.inc_count(); //increment c2• 23 c2.inc_count(); //increment c2 again• 24 cout << “\nc1=“ <<c1.get_count(); //display again• 25 cout << “\nc2=“ <<c2.get_count();• 26 return 0; // indicates successful termination• 27 • 28 } // end main

c1=0

c2=0

c1=1

c2=2

Constructors (con’t)• In the previous example, when an object of type Counter is first

created, we want it to be initialized to 0.• Alternatively, we could provide a zero_count() function, which

could always set count to 0. However, same function needs to be executed every time we created a Counter object.Counter c1;c1.zero_count();

• This function is called automatically whenever an object of type Counter is created. i.e. Counter c1,c2; //creates objects of type Counter

• This function sets the count variable to 0. so the effect of this single statement is to not only create two objects, but also to initialize their count variables to 0.

Copy Constructor

• We can also initialize an object with another object of the same type

• Surprisingly, we don’t need to create a special constructor for this; one is already built into all classes. It is called the default copy constructor

• It’s one-argument constructor whose argument is an object of the same class as the constructor

An example of Copy constructors• #include <iostream.h>• #include <conio.h>

• class Distance• {• private:• int feet;• float inches;• public:• Distance() //no-arg constructor• { }• Distance (int ft, float in) //two-arg constructor• {• feet=ft;• inches=in;• }• void getdist()• {• cout<<"\nEnter feet: "; cin>>feet;• cout<<"\nEnter inches: "; cin>>inches;• }• void showdist()• {• cout<<feet<<"\'"<<inches<<'\"';}• };• void main()• {• clrscr();• Distance dist1(11,6.25); //initialize dist1 constructor• Distance dist2(dist1); //pass object dist1 to constructor Distance • Distance dist3=dist1; //assign object that contained value to dust3 object

• cout<<"\ndist1= ";• dist1.showdist();• cout<<"\ndist2= ";• dist2.showdist();• cout<<"\ndist3= ";• dist3.showdist();• getch();• } // end main

dist1= 11’6.25”

dist2= 11’6.25”

dist3= 11’6.25”

Overloaded constructors• More than one constructor functions can be defined in one

class• When more than one constructor functions are defined, each

constructor is defined with a different set of parameters• “Defining more than one constructor with same name but

different set of parameters is called constructor overloading”• Constructor overloading is used to initialize different values to

class objects• When a program that uses the constructor overloading is

compiled, C++ complier checks the number of parameters, their order and data types and marks them differently

• When an object of the class is created, the corresponding constructor that matches the number of parameters of the object function is executed

Another example of constructor overloading

• 1 // constructor1.cpp• 2 // An example of a constructor overloading• 3 #include <iostream.h>• 4 • 5• 6• 7 • 8 class sum• 9 {• 10 public:• 11 sum (int l, int m, int n) // three-arg constructor• 12 { cout << “Sum of 3 integers is=“ << (l+m+n) <<endl; }• 13 sum (float l, float m) // two-arg constructor• 14 { cout << “Sum of 2 float is=“ << (l+m) <<endl; }• 15 };• 16• 17 void main()• 18 {• 19 sum x(6.2,2.2), y(7,6,8);• 20 } // end main

• In this above program, when the program is executed, the object x is created first and then the sum constructor function that has two integer type parameters is executed and similarly y object is created and the sum constructor function that has three integer type parameters is executed

Sum of 2 float is=8.4

Sum of 3 integers is=21

Destructors• Destructors

– Another function is called, when an object is destroyed– Same name as class

• Preceded with tilde (~)

– No arguments – Cannot be overloaded– Do not have a return value– Take no arguments– Deallocate memory that was allocated for the object by

the constructor– Performs “termination housekeeping

Destructor example

• class Foo{

private:int data;

public:Foo() { data = 0; }

//constructor~Foo() { }

//destructor};

An example of destructor• 1 // constructor1.cpp• 2 // An example of a destructor • 3 #include <iostream>• 4 • 5• 6• 7 • 8 class ping• 9 {• 10 public:• 11 ping() //no-arg constructor• 12 { cout << “This is a constructor function”<<endl; }• 13 ~ping() //destructor• 14 { cout << “This is a destructor function”<<endl; }• 15 };• 16• 17 int main()• 18 {• 19 ping x;• 20 int a,b;• 21 a=10;• 22 b=20;• 23 cout<<“The sum of two numbers is=“<<(a+b)<<endl;• 24 • 25 return 0; // indicates successful termination• 26 } // end main

• In this above program, when the program is executed, the constructor function is called, then prints out the sum of values of a and b, and then atlast the destructor function is executed

This is a constructor function

The sum of two numbers is=30

This is a destructor function

18

When Constructors and Destructors Are Called

• Order of constructor, destructor function calls– Global scope objects

• Constructors– Before any other function (including main)

• Destructors – When main terminates (or exit function called) – Not called if program terminates with abort

– Automatic local objects• Constructors

– When objects defined» Each time execution enters scope

• Destructors– When objects leave scope

» Execution exits block in which object defined– Not called if program ends with exit or abort

19

When Constructors and Destructors Are Called

• Order of constructor, destructor function calls• Constructors

– Exactly once– When execution reaches point where object defined

• Destructors – When main terminates or exit function called– Not called if program ends with abort

Friend Functions• Friends functions

– Non-member functions should be able to access an object’s private or protected data

– Free up the concept of data encapsulation and data hiding – Acts as a bridge b/w two classes

• Declaring friends– Function

• Precede function prototype with keyword friend

– All member functions of class ClassTwo as friends of class ClassOne

• Place declaration of formfriend class ClassTwo;

in ClassOne definition

An example of friends function• 1 // friend.cpp• 2 // An example of a friend function• 3 #include <iostream>• 4 • 5• 6• 7 class beta; //needed for frifunc declaration • 8 class alpha• 9 {• 10 private:• 11 int data;• 12 public:• 13 alpha() { data=3; } // no-arg constructor• 14 friend frifunc (alpha, beta); // friend function• 15 };• 16 class beta• 17 {• 18 private:• 19 int data;• 20 public:• 21 beta() { data=7; } // no-arg constructor• 22 friend frifunc (alpha, beta); // friend function• 23 };• 24 int frifunc(alpha a, beta b) //function declaration• 25 { return (a.data + b.data); } • 26 int main()• 27 {• 28 alpha aa;• 29 beta bb;• 30 cout << frifunc (aa, bb); //call the function• 31 return 0; // indicates successful termination• 32 • 33 } // end main

10

Friend function (con’t)• In the previous example, we make frifunc() to have access to both private

data members, so we make it a friend function• It is declared with the friend keyword in both classes:

friend int frifunc(alpha, beta); // can be placed anywhere in the class, does’nt matter if it goes in the public or the private section

• An object of each class is passed as an argument to the function frifunc(), and it accesses the private data member of both classes through these arguments.

• The function does’nt do much: add the data items and returns the sum. The main() program calls this function and prints the result

• Note: class “beta” is referred to in the declaration of the function frifunc() in the class “alpha”, so “beta” must be declared before “alpha”. Hence the declaration

class beta; //at the beginning of the program

Another example of friends function• 1 // friend1.cpp• 2 // An example of a friend function• 3 #include <iostream>• 4 • 5• 6 class y; //needed for frifunc declaration• 7• 8 class x• 9 {• 10 private:• 11 int m;• 12 public:• 13 x() { m=10; } // no-arg constructor• 14 friend int abc (a,b); // friend function• 15 };• 16 class y• 17 {• 18 private:• 19 int n;• 20 public:• 21 y() { n=10; } // no-arg constructor• 22 friend int abc (a,b); // friend function• 23 };• 24 int abc (x c1, y c2 ) //function declaration• 25 { return (c1.m + c2.n); } • 26 int main()• 27 {• 28 x a;• 29 y b;• 30 cout << Sum of two numbers = “<<abc (a, b); //call the function• 31 return 0; // indicates successful termination• 32 • 33 } // end main

sum of two numbers=20

Friend function (con’t)• In the previous example, we make abc() to have access to both private

data members, so we make it a friend function• It is declared with the friend keyword in both classes:

friend int abc(a, b); // can be placed anywhere in the class, does’nt matter if it goes in the public or the private section

• An object of each class is passed as an argument to the function abc(), and it accesses the private data member of both classes through these arguments.

• The function does’nt do much: add the data items and returns the sum. The main() program calls this function and prints the result

• Note: class “y” is referred to in the declaration of the function abc() in the class “x”, so “y” must be declared before “x”. Hence the declaration

class y; //at the beginning of the program

Friend classes

• The member functions of a class can all be made friends at the same time when you make the entire class a friend

• The program FRICLASS shows how this looks

An example of friends class• 1 // friendclass.cpp• 2 // An example of a friend classes• 3 #include <iostream>• 4 • 5• 6• 7 class alpha• 9 {• 10 private:• 11 int data1;• 12 public:• 13 alpha() { data1=99; } // no-arg constructor• 14 friend class beta; // beta is a friend class• 15 };• 16 class beta• 17 { // all member functions can• 18 public: // access private alpha data• 19 void func1(alpha a) { cout << “\ndata1=“ <<a.data1; }• 20 void func2(alpha a) { cout << “\ndata1=“ <<a.data1; }• 21 void func3(alpha a) { cout << “\ndata1=“ <<a.data1; }• 22 };• 23 int main()• 24 {• 25 alpha aa;• 26 beta bb;• 27 bb.func1(aa);• 28 bb.func2(aa);• 29 bb.func3(aa);• 28 return 0; // indicates successful termination• 29 • 30 } // end main

data1=99

data1=99

data1=99

Friend classes (con’t)

• In the class “alpha” the entire class “beta” is proclaimed a friend

• Now all the member functions of “beta” can access the private data of “alpha” (in this program the single data item data1)

• Note that in the friend declaration we specify that “beta” is a class using the class keyword:friend class beta;

31

friend Functions and friend Classes (con’t)

• Properties of friendship– Friendship granted, not taken

• Class B friend of class A– Class A must explicitly declare class B friend

– Not symmetric • Class B friend of class A• Class A not necessarily friend of class B

– Not transitive • Class A friend of class B • Class B friend of class C• Class A not necessarily friend of Class C

32

Using the this Pointer• this pointer

– Allows object to access own address– Implicitly reference member data and functions – Magic pointer named “this”, which points to the

object itself– To find out the address of the object of which it is

a member– Can also be treated like any other pointer to an

object, and can be used to access the data in the object it points to

An example of without this pointer• 1 // where.cpp• 2 // An example of a this pointer• 3 #include<iostream.h>• 4 #include<conio.h>• 5 class A• 6 {• 7 private:• 8 int a;• 9 int b;• 10• 11 • 12 public: • 13 • 14 void getdata(int a, int c)• 15 {• 16 a = a;• 17 b = c;• 18 }• 19 void display()• 20 {• 21 cout<<"\n"<<a;• 22 cout<<"\n";• 23 cout<<b<<"\n";• 24 }• 25 };• 26 int main()• 27 {• 28 clrscr();• 29 A obj1;• 30 obj1.display();• 31 obj1.getdata(2, 4);• 32 obj1.display();• 33 getch();• 34 } return 0; // indicates successful termination• 25 • 26 } // end main

0

7713

0

4

An example of with this pointer• 1 // where.cpp• 2 // An example of a this pointer• 3 #include<iostream.h>• 4 #include<conio.h>• 5 class A• 6 {• 7 private:• 8 int a;• 9 int b;• 10• 11 • 12 public: • 13 • 14 void getdata(int a, int c)• 15 {• 16 this->a = a;• 17 b = c;• 18 }• 19 void display()• 20 {• 21 cout<<"\n"<<a;• 22 cout<<"\n";• 23 cout<<b<<"\n";• 24 }• 25 };• 26 int main()• 27 {• 28 clrscr();• 29 A obj1;• 30 obj1.display();• 31 obj1.getdata(2, 4);• 32 obj1.display();• 33 getch();• 34 } return 0; // indicates successful termination• 25 • 26 } // end main

0

7713

2

4

An example of this pointer• 1 // where.cpp• 2 // An example of a this pointer• 3 #include <iostream>• 4 • 5• 6• 7 class where• 9 {• 10 private:• 11 char carray[10]; //occupies 10 bytes• 12 public:• 13 void reveal()• 14 { cout << “\nMy object’s address is” << this; }• 15 };• 16 int main()• 17 {• 18 where w1,w2,w3; //make three objects• 19 w1.reveal(); //see where they are• 20 w2.reveal();• 21 w3.reveal();• 22 return 0; // indicates successful termination• 23 • 24 } // end main

My object’s address is 0x8f4effec

My object’s address is 0x8f4effe2

My object’s address is 0x8f4effd8

this pointer (con’t)

• In the previous example, the main() program creates three objects of type “where”

• It then asks each object to print its address, using the reveal() member function

• The function reveal() prints out the value of the this pointer

• Since the data in each object consists of an array of 10 bytes, the objects are 10 bytes apart in the memory

Accessing Member Data with “this”

• When you call a member function, it comes into existence with the value of “this” set to the address of the object for which it was called

• The “this” pointer can be treated like any other pointer to an object, and can thus be used to access the data in the object it points to as shown in dothis.cpp program:

Another example of this pointer• 1 // dothis.cpp• 2 // the this pointer referring to data• 3 #include <iostream>• 4 • 5 using std::cout;• 6 using std::endl;• 7 class what• 9 {• 10 private:• 11 int alpha;• 12 public:• 13 void tester()• 14 { this-> alpha = 11; //same as alpha = 11• 15 cout << this->alpha; } //same as cout << alpha• 16 };• 17 int main()• 18 {• 19 what w;• 20 w.tester();• 21 return 0; // indicates successful termination• 22 • 23 } // end main

11

this pointer (con’t)

• This previous program prints out the value 11• Notice that the tester() member function

accesses the variable “alpha” asthis->alpha

• This is exactly the same as referring to alpha directly

44

Dynamic Memory Management with Operators new and delete

• new– Consider

Time *timePtr;timePtr = new Time;

– new operator• Creates object of proper size for type Time

– Error if no space in memory for object• Calls default constructor for object• Returns pointer of specified type

– Providing initializersdouble *ptr = new double( 3.14159 );Time *timePtr = new Time( 12, 0, 0 );

– Allocating arraysint *gradesArray = new int[ 10 ];

45

Dynamic Memory Management with Operators new and delete

• delete– Destroy dynamically allocated object and free space– Consider

delete timePtr;

– Operator delete• Calls destructor for object• Deallocates memory associated with object

– Memory can be reused to allocate other objects

– Deallocating arraysdelete [] gradesArray;

– Deallocates array to which gradesArray points• If pointer to array of objects

» First calls destructor for each object in array» Then deallocates memory

An example of new and delete operator

• 1 // newintro.cpp• 2 // introduces operator new and delete operator• 3 #include <iostream.h>• 4 #include <string.h> //for strcpy• 5• 6• 7• 8 int main()• 9• 10 {• 11 char *str = “idle hands are the devil’s workshop.”;• 12 int len = strlen(str); //get length of str• 13 char *ptr; //make a pointer to char• 14 ptr = new char[len+1] //set aside memory: string • 15 strcpy(ptr,str) //copy str to new memory area

ptr• 16 cout << endl << “ptr =“ << ptr; //show that str is now in ptr• 17 delete[] ptr; //release ptr’s memory• 18 return 0; // indicates successful termination• 19 • 20 } // end main

idle hands are the devil’s workshop.

Syntax of new operator

char * ptr;

ptr = new char[len+1];

Pointer

Keyword

Data type of variables

Number of type char variables

Memory obtained by new operator

Memory obtained byptr = new char[len+1]

f700

f700ptr

Len+1

Delete operator

ptr = new someclass; //allocate a single //object

delete ptr //no brackets //following delete

An example of new and delete operator• 1 // newintro.cpp• 2 // using new to get memory for strings• 3 #include <iostream.h>• 4 #include <string.h> //for strcpy, etc• 5• 6• 7• 8 class String //user-defined string type• 9 {• 10 private:• 11 char* str; //pointer to string• 12 public:• 13 String (char* s) //constructor, one arg• 14 {• 15 int length = strlen(s); //length of string argument• 16 str = new char[length]; //get memory• 17 strcpy(str, s); //copy argument to it• 18 }• 19 ~String() //destructor• 20 {• 21 delete[] str; //release memory• 22 }• 23 void display() //display the string• 24 {• 25 cout <<“s1= “<<str;• 26 } };• 27 int main()• 28 {• 29 String s1 = “Who knows nothing doubts nothing.”;• 30 s1.display();• 32 return 0; // indicates successful termination• 33 • 34 } // end main

a1=Who knows nothing doubts nothing.

Recommended