SlideShare uma empresa Scribd logo
1 de 52
1 
Week 9-10 
Outline 
• 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
I am constructor 
I am constructor 
I am constructor 
• 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
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
Sum of 2 float is=8.4 
Sum of 3 integers is=21 
• 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
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
This is a constructor function 
The sum of two numbers is=30 
This is a destructor function 
• 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
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 form 
friend 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” as 
this->alpha 
• This is exactly the same as referring to alpha 
directly
Dynamic Memory Management 
with Operators new and delete 
• new 
44 
– 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 initializers 
double *ptr = new double( 3.14159 ); 
Time *timePtr = new Time( 12, 0, 0 ); 
– Allocating arrays 
int *gradesArray = new int[ 10 ];
Dynamic Memory Management 
with Operators new and delete 
• delete 
45 
– 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 arrays 
delete [] 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; 
Pointer 
ptr = new char[len+1]; 
Keyword 
Number of type 
char variables 
Data type of 
variables
Memory obtained by new operator 
f700 
Memory obtained by 
ptr = new char[len+1] 
f700 
ptr 
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.

Mais conteúdo relacionado

Mais procurados

Reactive, component 그리고 angular2
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2Jeado Ko
 
The Ring programming language version 1.8 book - Part 86 of 202
The Ring programming language version 1.8 book - Part 86 of 202The Ring programming language version 1.8 book - Part 86 of 202
The Ring programming language version 1.8 book - Part 86 of 202Mahmoud Samir Fayed
 
Cocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magicCocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magicBadoo Development
 
ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersBartosz Kosarzycki
 
Cocoaheads Meetup / Kateryna Trofimenko / Feature development
Cocoaheads Meetup / Kateryna Trofimenko / Feature developmentCocoaheads Meetup / Kateryna Trofimenko / Feature development
Cocoaheads Meetup / Kateryna Trofimenko / Feature developmentBadoo Development
 
Pattern printing programs
Pattern printing programsPattern printing programs
Pattern printing programsMukesh Tekwani
 
Tutconstructordes
TutconstructordesTutconstructordes
TutconstructordesNiti Arora
 
C# console programms
C# console programmsC# console programms
C# console programmsYasir Khan
 
Constructors.16
Constructors.16Constructors.16
Constructors.16myrajendra
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsBartosz Kosarzycki
 
HKG15-207: Advanced Toolchain Usage Part 3
HKG15-207: Advanced Toolchain Usage Part 3HKG15-207: Advanced Toolchain Usage Part 3
HKG15-207: Advanced Toolchain Usage Part 3Linaro
 
JavaScript 2016 for C# Developers
JavaScript 2016 for C# DevelopersJavaScript 2016 for C# Developers
JavaScript 2016 for C# DevelopersRick Beerendonk
 
81818088 isc-class-xii-computer-science-project-java-programs
81818088 isc-class-xii-computer-science-project-java-programs81818088 isc-class-xii-computer-science-project-java-programs
81818088 isc-class-xii-computer-science-project-java-programsAbhishek Jena
 

Mais procurados (20)

Constructors & destructors
Constructors & destructorsConstructors & destructors
Constructors & destructors
 
Reactive, component 그리고 angular2
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2
 
The Ring programming language version 1.8 book - Part 86 of 202
The Ring programming language version 1.8 book - Part 86 of 202The Ring programming language version 1.8 book - Part 86 of 202
The Ring programming language version 1.8 book - Part 86 of 202
 
Cocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magicCocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magic
 
ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developers
 
C# labprograms
C# labprogramsC# labprograms
C# labprograms
 
Cocoaheads Meetup / Kateryna Trofimenko / Feature development
Cocoaheads Meetup / Kateryna Trofimenko / Feature developmentCocoaheads Meetup / Kateryna Trofimenko / Feature development
Cocoaheads Meetup / Kateryna Trofimenko / Feature development
 
Pattern printing programs
Pattern printing programsPattern printing programs
Pattern printing programs
 
Tutconstructordes
TutconstructordesTutconstructordes
Tutconstructordes
 
C#
C#C#
C#
 
C# console programms
C# console programmsC# console programms
C# console programms
 
C# 6.0 Preview
C# 6.0 PreviewC# 6.0 Preview
C# 6.0 Preview
 
Constructors.16
Constructors.16Constructors.16
Constructors.16
 
Day 1
Day 1Day 1
Day 1
 
A Taste of Dotty
A Taste of DottyA Taste of Dotty
A Taste of Dotty
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
What's New in C++ 11?
What's New in C++ 11?What's New in C++ 11?
What's New in C++ 11?
 
HKG15-207: Advanced Toolchain Usage Part 3
HKG15-207: Advanced Toolchain Usage Part 3HKG15-207: Advanced Toolchain Usage Part 3
HKG15-207: Advanced Toolchain Usage Part 3
 
JavaScript 2016 for C# Developers
JavaScript 2016 for C# DevelopersJavaScript 2016 for C# Developers
JavaScript 2016 for C# Developers
 
81818088 isc-class-xii-computer-science-project-java-programs
81818088 isc-class-xii-computer-science-project-java-programs81818088 isc-class-xii-computer-science-project-java-programs
81818088 isc-class-xii-computer-science-project-java-programs
 

Semelhante a Friend this-new&delete

Semelhante a Friend this-new&delete (20)

Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
C++ Functions.pptx
C++ Functions.pptxC++ Functions.pptx
C++ Functions.pptx
 
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxconstructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
OOP.pptx
OOP.pptxOOP.pptx
OOP.pptx
 
constructor in object oriented program.pptx
constructor in object oriented program.pptxconstructor in object oriented program.pptx
constructor in object oriented program.pptx
 
Intro to C++
Intro to C++Intro to C++
Intro to C++
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
 
Classes
ClassesClasses
Classes
 
Constructor and Destructors in C++
Constructor and Destructors in C++Constructor and Destructors in C++
Constructor and Destructors in C++
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
 
21CSC101T best ppt ever OODP UNIT-2.pptx
21CSC101T best ppt ever OODP UNIT-2.pptx21CSC101T best ppt ever OODP UNIT-2.pptx
21CSC101T best ppt ever OODP UNIT-2.pptx
 
Cs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALCs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUAL
 
Oops presentation
Oops presentationOops presentation
Oops presentation
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
Operator overload rr
Operator overload  rrOperator overload  rr
Operator overload rr
 
Standardizing JavaScript Decorators in TC39 (Full Stack Fest 2019)
Standardizing JavaScript Decorators in TC39 (Full Stack Fest 2019)Standardizing JavaScript Decorators in TC39 (Full Stack Fest 2019)
Standardizing JavaScript Decorators in TC39 (Full Stack Fest 2019)
 
Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4
 
Oop presentation
Oop presentationOop presentation
Oop presentation
 

Último

Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Dana Luther
 
Magic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMagic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMartaLoveguard
 
Contact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New DelhiContact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New Delhimiss dipika
 
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)Christopher H Felton
 
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书rnrncn29
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Sonam Pathan
 
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书zdzoqco
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITMgdsc13
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012rehmti665
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa494f574xmv
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一Fs
 
Top 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxTop 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxDyna Gilbert
 
Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Paul Calvano
 
Intellectual property rightsand its types.pptx
Intellectual property rightsand its types.pptxIntellectual property rightsand its types.pptx
Intellectual property rightsand its types.pptxBipin Adhikari
 
Q4-1-Illustrating-Hypothesis-Testing.pptx
Q4-1-Illustrating-Hypothesis-Testing.pptxQ4-1-Illustrating-Hypothesis-Testing.pptx
Q4-1-Illustrating-Hypothesis-Testing.pptxeditsforyah
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一Fs
 
Elevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New OrleansElevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New Orleanscorenetworkseo
 
SCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is prediSCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is predieusebiomeyer
 

Último (20)

Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
 
Magic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMagic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptx
 
Contact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New DelhiContact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New Delhi
 
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
 
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170
 
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITM
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
 
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
 
Top 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxTop 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptx
 
Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24
 
Intellectual property rightsand its types.pptx
Intellectual property rightsand its types.pptxIntellectual property rightsand its types.pptx
Intellectual property rightsand its types.pptx
 
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
 
Q4-1-Illustrating-Hypothesis-Testing.pptx
Q4-1-Illustrating-Hypothesis-Testing.pptxQ4-1-Illustrating-Hypothesis-Testing.pptx
Q4-1-Illustrating-Hypothesis-Testing.pptx
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
 
Elevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New OrleansElevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New Orleans
 
SCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is prediSCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is predi
 

Friend this-new&delete

  • 1. 1 Week 9-10 Outline • Constructors • Destructors • Friend functions • This pointer • Dynamic Memory allocation with NEW and DELETE operators
  • 2. 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
  • 3. 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
  • 4. I am constructor I am constructor I am constructor • 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
  • 5. 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
  • 7. 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.
  • 8. 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
  • 9. 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
  • 10. dist1= 11’6.25” dist2= 11’6.25” dist3= 11’6.25”
  • 11. 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
  • 12. 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
  • 13. Sum of 2 float is=8.4 Sum of 3 integers is=21 • 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
  • 14. 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
  • 15. Destructor example • class Foo { private: int data; public: Foo() { data = 0; } //constructor ~Foo() { } //destructor };
  • 16. 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
  • 17. This is a constructor function The sum of two numbers is=30 This is a destructor function • 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
  • 18. 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. 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
  • 20. 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 form friend class ClassTwo; in ClassOne definition
  • 21. 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
  • 22. 10
  • 23. 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
  • 24. 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
  • 25. sum of two numbers=20
  • 26. 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
  • 27. 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
  • 28. 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
  • 30. 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. 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. 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
  • 33. 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
  • 34. 0 7713 0 4
  • 35. 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
  • 36. 0 7713 2 4
  • 37. 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
  • 38. My object’s address is 0x8f4effec My object’s address is 0x8f4effe2 My object’s address is 0x8f4effd8
  • 39. 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
  • 40. 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:
  • 41. 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
  • 42. 11
  • 43. this pointer (con’t) • This previous program prints out the value 11 • Notice that the tester() member function accesses the variable “alpha” as this->alpha • This is exactly the same as referring to alpha directly
  • 44. Dynamic Memory Management with Operators new and delete • new 44 – 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 initializers double *ptr = new double( 3.14159 ); Time *timePtr = new Time( 12, 0, 0 ); – Allocating arrays int *gradesArray = new int[ 10 ];
  • 45. Dynamic Memory Management with Operators new and delete • delete 45 – 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 arrays delete [] gradesArray; – Deallocates array to which gradesArray points • If pointer to array of objects » First calls destructor for each object in array » Then deallocates memory
  • 46. 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
  • 47. idle hands are the devil’s workshop.
  • 48. Syntax of new operator char * ptr; Pointer ptr = new char[len+1]; Keyword Number of type char variables Data type of variables
  • 49. Memory obtained by new operator f700 Memory obtained by ptr = new char[len+1] f700 ptr Len+1
  • 50. Delete operator ptr = new someclass; //allocate a single //object delete ptr //no brackets //following delete
  • 51. 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
  • 52. a1=Who knows nothing doubts nothing.