SlideShare a Scribd company logo
1
Constructors and Destructors
in C++
2
Constructors
• A special member function whose task is to initialize the objects of its class.
• It has the same name as the class name.
• It is invoked whenever an object of its associated class is created.
• A constructor is declared and defined as follows:
class integer
{
int m, n;
public:
integer(void); //constructor declared
…..
…..
};
3
integer :: integer(void) // constructor defined
{
m=0; n=0’
}
• When a class contains a constructor, it is guaranteed that an object
created by the class will be initialized automatically. For example:
integer int1; //object int1 created
• The above statement not only creates the object int1 of type integer but
also initializes its data members m and n to zero.
• A constructor that accepts no parameters is called the default constructor.
• If no such constructor is defined, then the compiler supplies a default
constructor.
4
Special characteristics of constructors
• They should be declared in the public section.
• They are invoked automatically when the objects are created.
• They do not have return types, not even void and therefore, they
cannot return values.
• They cannot be inherited, though a derived class can call the base
class constructor.
• They can have default arguments.
5
Parameterized Constructors
• The constructors that can take arguments are called parameterized
constructors.
• When a constructor has been parameterized, the object declaration
statement such as
integer int1;
• May not work. We must pass the initial values as arguments to the
constructor function when an object is declared.
• This can be done in two ways:
• By calling the constructor explicitly
• By calling the constructor implicitly
6
#include<iostream>
using namespace std;
class integer
{
int m, n;
public:
integer(int, int);
void display(void)
{
cout<< “m = ”<<m<<“n”;
cout<< “n = ”<<n<<“n”;
}
};
7
integer :: integer(int x, int y)
{
m=x; n=y;
}
int main()
{
integer int1(0, 100); //constructor called implicitly
integer int2 = integer(25, 75); //constructor called explicitly
cout<<“nOBJECT1”<<“n”;
int1.display();
cout<<“nOBJECT2”<<“n”;
int2.display();
return 0;
}
8
output:
OBJECT1
m=0
n=100
OBJECT2
m=25
n=75
9
Multiple constructors in a class
• A class can have more than one constructors. For example, a class can be defined as follows:
class integer
{
int m, n;
public:
integer() //constructor 1
{ m=0; n=0;}
integer(int a, int b) //constructor 2
{ m = a; n = b; }
integer(integer &i) //constructor 3
{ m = i.m; n = i.n; }
};
10
• This declares three constructors for an integer object.
• The first constructor receives no arguments, the second constructor receives two
integer arguments and the third receives one integer object as an argument.
• For example:
integer I1;
• would invoke the first constructor and set both m and n of I1 to zero.
integer I2(20, 40);
• would call the second constructor which will initialize the data members m and n of
I2 to 20 and 40 respectively.
integer I3(I2);
• would invoke the third constructor which copies the values of I2 into I3. It sets the
value of every data element of I3 to the value of the corresponding data element
of I2.
• Such a constructor is called the copy constructor.
• When more than one constructor function is defined in a class, the constructor is
said to be overloaded.
11
Copy Constructor
• A copy constructor is used to declare and initialize an object from another
object. For example:
integer I2(I1);
• The above statement would define the object I2 and at the same time
initialize it to the values of I1. Another form of above statement is
integer I2 = I1;
• The process of initializing through a copy constructor is known as copy
initialization.
• Note that the statement
I2 = I1;
will not invoke the copy constructor. However, if I1 and I2 are objects, this
statement is legal and simply assigns values of I1 to I2, member-by-member.
12
• A copy constructor takes a reference to an object of the same class itself as an
argument. Example program:
#include<iostream>
using namespace std;
class code
{
int id;
public:
code() { } //constructor 1
code(int a) { id = a; } //constructor 2
code(code &x) //copy constructor
{ id = x.id; //copy in the value
}
13
void display(void)
{ cout << id; }
};
int main()
{
code A(100); //object A is created and initialized
code B(A); //copy constructor called
code C = A; // copy constructor called again
code D; // D is created but not initialized
D = A; // copy constructor not called
cout << “n id of A: ”; A.display();
cout << “n id of B: ”; B.display();
cout << “n id of C: ”; C.display();
cout << “n id of D: ”; D.display();
return 0;
}
14
• The output is as shown below:
id of A: 100
id of B: 100
id of C: 100
id of D: 100
• Note: A reference variable has been used as an argument to the copy
constructor. We cannot pass the argument by value to a copy
constructor.
15
Destructors
• A destructor is used to destroy the objects that have been created by
a constructor.
• Similar to constructor, a destructor is a member function whose name
is the same as the class name but is preceded by a tilde. For example,
the destructor for the class integer can be defined as shown below:
~integer () { }
• A destructor never takes any argument nor does it return any value. It
will be invoked implicitly by the compiler upon exit from the program
to clean up storage that is no longer accessible.
16
#include<iostream>
using namespace std;
int count = 0;
class alpha
{
public:
alpha()
{ count++;
cout <<“nNo. of object created ” << count;
}
~alpha()
{ cout <<“nNo. of object destroyed ” << count;
count--;
}
};
17
int main()
{
cout <<“nnEnter Mainn”;
alpha A1, A2, A3, A4;
{ cout <<“nnEnter Block1n”;
alpha A5;
}
{ cout <<“nnEnter Block2n”;
alpha A6;
}
cout <<“nnRe-enter Mainn”;
return 0;
}
18
Enter Main
No of object created 1
No of object created 2
No of object created 3
No of object created 4
Enter Block1
No of object created 5
No of object destroyed 5
Enter Block2
No of object created 5
No of object destroyed 5
Re-enter Main
No of object destroyed 4
No of object destroyed 3
No of object destroyed 2
No of object destroyed 1

More Related Content

PDF
Constructors & Destructors [Compatibility Mode].pdf
LadallaRajKumar
 
PPT
Constructors and destructors in C++
RAJ KUMAR
 
PDF
Constructors and destructors
Prof. Dr. K. Adisesha
 
PPT
Constructor,destructors cpp
रमन सनौरिया
 
PDF
Constructor and Destructor
Kamal Acharya
 
PPTX
constructors and destructors
Akshaya Parida
 
PPT
Friend this-new&delete
Shehzad Rizwan
 
PPTX
Constructor and desturctor
Somnath Kulkarni
 
Constructors & Destructors [Compatibility Mode].pdf
LadallaRajKumar
 
Constructors and destructors in C++
RAJ KUMAR
 
Constructors and destructors
Prof. Dr. K. Adisesha
 
Constructor,destructors cpp
रमन सनौरिया
 
Constructor and Destructor
Kamal Acharya
 
constructors and destructors
Akshaya Parida
 
Friend this-new&delete
Shehzad Rizwan
 
Constructor and desturctor
Somnath Kulkarni
 

Similar to Constructors and Destructors in C++.pptx (20)

PPTX
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
Muhammad Hammad Waseem
 
PPT
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
Venugopalavarma Raja
 
PPTX
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
AshrithaRokkam
 
PPTX
Constructors and Destructors
Keyur Vadodariya
 
PPTX
Constructors in C++.pptx
Rassjb
 
PDF
Constructors or destructors unit(II).pdf
malviyatanishk8
 
PPTX
constructor & destructor in cpp
gourav kottawar
 
PPTX
constructor & destructor in cpp
gourav kottawar
 
PPT
ConsTRUCTION AND DESTRUCTION
Shweta Shah
 
PPT
Constructor and destructor in C++
Carelon Global Solutions
 
PPTX
constructors
DeepikaT13
 
PPT
Constructors and destructors in C++ part 2
Carelon Global Solutions
 
PPTX
Constructors & Destructors
Rokonuzzaman Rony
 
PDF
Constructors destructors
Pranali Chaudhari
 
PPTX
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
DeepasCSE
 
PPTX
Constructors and Destructor_detilaed contents.pptx
vijayaazeem
 
PPTX
OOP-Lecture-05 (Constructor_Destructor).pptx
SirRafiLectures
 
PDF
Constructors and Destructors
Dr Sukhpal Singh Gill
 
PPTX
constructor in object oriented program.pptx
urvashipundir04
 
DOCX
Constructor-Types of Constructor:default,parameterized,copy constructor-Destr...
rajalakshmisf687
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
Muhammad Hammad Waseem
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
Venugopalavarma Raja
 
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
AshrithaRokkam
 
Constructors and Destructors
Keyur Vadodariya
 
Constructors in C++.pptx
Rassjb
 
Constructors or destructors unit(II).pdf
malviyatanishk8
 
constructor & destructor in cpp
gourav kottawar
 
constructor & destructor in cpp
gourav kottawar
 
ConsTRUCTION AND DESTRUCTION
Shweta Shah
 
Constructor and destructor in C++
Carelon Global Solutions
 
constructors
DeepikaT13
 
Constructors and destructors in C++ part 2
Carelon Global Solutions
 
Constructors & Destructors
Rokonuzzaman Rony
 
Constructors destructors
Pranali Chaudhari
 
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
DeepasCSE
 
Constructors and Destructor_detilaed contents.pptx
vijayaazeem
 
OOP-Lecture-05 (Constructor_Destructor).pptx
SirRafiLectures
 
Constructors and Destructors
Dr Sukhpal Singh Gill
 
constructor in object oriented program.pptx
urvashipundir04
 
Constructor-Types of Constructor:default,parameterized,copy constructor-Destr...
rajalakshmisf687
 
Ad

Recently uploaded (20)

PPT
1. SYSTEMS, ROLES, AND DEVELOPMENT METHODOLOGIES.ppt
zilow058
 
PPTX
Inventory management chapter in automation and robotics.
atisht0104
 
PDF
Zero Carbon Building Performance standard
BassemOsman1
 
PDF
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
PPTX
Chapter_Seven_Construction_Reliability_Elective_III_Msc CM
SubashKumarBhattarai
 
PDF
Zero carbon Building Design Guidelines V4
BassemOsman1
 
PPTX
MT Chapter 1.pptx- Magnetic particle testing
ABCAnyBodyCanRelax
 
PDF
flutter Launcher Icons, Splash Screens & Fonts
Ahmed Mohamed
 
PPTX
database slide on modern techniques for optimizing database queries.pptx
aky52024
 
PPTX
MSME 4.0 Template idea hackathon pdf to understand
alaudeenaarish
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PDF
Packaging Tips for Stainless Steel Tubes and Pipes
heavymetalsandtubes
 
DOCX
SAR - EEEfdfdsdasdsdasdasdasdasdasdasdasda.docx
Kanimozhi676285
 
PDF
20ME702-Mechatronics-UNIT-1,UNIT-2,UNIT-3,UNIT-4,UNIT-5, 2025-2026
Mohanumar S
 
PDF
Advanced LangChain & RAG: Building a Financial AI Assistant with Real-Time Data
Soufiane Sejjari
 
PPTX
easa module 3 funtamental electronics.pptx
tryanothert7
 
PDF
Unit I Part II.pdf : Security Fundamentals
Dr. Madhuri Jawale
 
PPT
SCOPE_~1- technology of green house and poyhouse
bala464780
 
PDF
2025 Laurence Sigler - Advancing Decision Support. Content Management Ecommer...
Francisco Javier Mora Serrano
 
PPTX
22PCOAM21 Session 1 Data Management.pptx
Guru Nanak Technical Institutions
 
1. SYSTEMS, ROLES, AND DEVELOPMENT METHODOLOGIES.ppt
zilow058
 
Inventory management chapter in automation and robotics.
atisht0104
 
Zero Carbon Building Performance standard
BassemOsman1
 
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
Chapter_Seven_Construction_Reliability_Elective_III_Msc CM
SubashKumarBhattarai
 
Zero carbon Building Design Guidelines V4
BassemOsman1
 
MT Chapter 1.pptx- Magnetic particle testing
ABCAnyBodyCanRelax
 
flutter Launcher Icons, Splash Screens & Fonts
Ahmed Mohamed
 
database slide on modern techniques for optimizing database queries.pptx
aky52024
 
MSME 4.0 Template idea hackathon pdf to understand
alaudeenaarish
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
Packaging Tips for Stainless Steel Tubes and Pipes
heavymetalsandtubes
 
SAR - EEEfdfdsdasdsdasdasdasdasdasdasdasda.docx
Kanimozhi676285
 
20ME702-Mechatronics-UNIT-1,UNIT-2,UNIT-3,UNIT-4,UNIT-5, 2025-2026
Mohanumar S
 
Advanced LangChain & RAG: Building a Financial AI Assistant with Real-Time Data
Soufiane Sejjari
 
easa module 3 funtamental electronics.pptx
tryanothert7
 
Unit I Part II.pdf : Security Fundamentals
Dr. Madhuri Jawale
 
SCOPE_~1- technology of green house and poyhouse
bala464780
 
2025 Laurence Sigler - Advancing Decision Support. Content Management Ecommer...
Francisco Javier Mora Serrano
 
22PCOAM21 Session 1 Data Management.pptx
Guru Nanak Technical Institutions
 
Ad

Constructors and Destructors in C++.pptx

  • 2. 2 Constructors • A special member function whose task is to initialize the objects of its class. • It has the same name as the class name. • It is invoked whenever an object of its associated class is created. • A constructor is declared and defined as follows: class integer { int m, n; public: integer(void); //constructor declared ….. ….. };
  • 3. 3 integer :: integer(void) // constructor defined { m=0; n=0’ } • When a class contains a constructor, it is guaranteed that an object created by the class will be initialized automatically. For example: integer int1; //object int1 created • The above statement not only creates the object int1 of type integer but also initializes its data members m and n to zero. • A constructor that accepts no parameters is called the default constructor. • If no such constructor is defined, then the compiler supplies a default constructor.
  • 4. 4 Special characteristics of constructors • They should be declared in the public section. • They are invoked automatically when the objects are created. • They do not have return types, not even void and therefore, they cannot return values. • They cannot be inherited, though a derived class can call the base class constructor. • They can have default arguments.
  • 5. 5 Parameterized Constructors • The constructors that can take arguments are called parameterized constructors. • When a constructor has been parameterized, the object declaration statement such as integer int1; • May not work. We must pass the initial values as arguments to the constructor function when an object is declared. • This can be done in two ways: • By calling the constructor explicitly • By calling the constructor implicitly
  • 6. 6 #include<iostream> using namespace std; class integer { int m, n; public: integer(int, int); void display(void) { cout<< “m = ”<<m<<“n”; cout<< “n = ”<<n<<“n”; } };
  • 7. 7 integer :: integer(int x, int y) { m=x; n=y; } int main() { integer int1(0, 100); //constructor called implicitly integer int2 = integer(25, 75); //constructor called explicitly cout<<“nOBJECT1”<<“n”; int1.display(); cout<<“nOBJECT2”<<“n”; int2.display(); return 0; }
  • 9. 9 Multiple constructors in a class • A class can have more than one constructors. For example, a class can be defined as follows: class integer { int m, n; public: integer() //constructor 1 { m=0; n=0;} integer(int a, int b) //constructor 2 { m = a; n = b; } integer(integer &i) //constructor 3 { m = i.m; n = i.n; } };
  • 10. 10 • This declares three constructors for an integer object. • The first constructor receives no arguments, the second constructor receives two integer arguments and the third receives one integer object as an argument. • For example: integer I1; • would invoke the first constructor and set both m and n of I1 to zero. integer I2(20, 40); • would call the second constructor which will initialize the data members m and n of I2 to 20 and 40 respectively. integer I3(I2); • would invoke the third constructor which copies the values of I2 into I3. It sets the value of every data element of I3 to the value of the corresponding data element of I2. • Such a constructor is called the copy constructor. • When more than one constructor function is defined in a class, the constructor is said to be overloaded.
  • 11. 11 Copy Constructor • A copy constructor is used to declare and initialize an object from another object. For example: integer I2(I1); • The above statement would define the object I2 and at the same time initialize it to the values of I1. Another form of above statement is integer I2 = I1; • The process of initializing through a copy constructor is known as copy initialization. • Note that the statement I2 = I1; will not invoke the copy constructor. However, if I1 and I2 are objects, this statement is legal and simply assigns values of I1 to I2, member-by-member.
  • 12. 12 • A copy constructor takes a reference to an object of the same class itself as an argument. Example program: #include<iostream> using namespace std; class code { int id; public: code() { } //constructor 1 code(int a) { id = a; } //constructor 2 code(code &x) //copy constructor { id = x.id; //copy in the value }
  • 13. 13 void display(void) { cout << id; } }; int main() { code A(100); //object A is created and initialized code B(A); //copy constructor called code C = A; // copy constructor called again code D; // D is created but not initialized D = A; // copy constructor not called cout << “n id of A: ”; A.display(); cout << “n id of B: ”; B.display(); cout << “n id of C: ”; C.display(); cout << “n id of D: ”; D.display(); return 0; }
  • 14. 14 • The output is as shown below: id of A: 100 id of B: 100 id of C: 100 id of D: 100 • Note: A reference variable has been used as an argument to the copy constructor. We cannot pass the argument by value to a copy constructor.
  • 15. 15 Destructors • A destructor is used to destroy the objects that have been created by a constructor. • Similar to constructor, a destructor is a member function whose name is the same as the class name but is preceded by a tilde. For example, the destructor for the class integer can be defined as shown below: ~integer () { } • A destructor never takes any argument nor does it return any value. It will be invoked implicitly by the compiler upon exit from the program to clean up storage that is no longer accessible.
  • 16. 16 #include<iostream> using namespace std; int count = 0; class alpha { public: alpha() { count++; cout <<“nNo. of object created ” << count; } ~alpha() { cout <<“nNo. of object destroyed ” << count; count--; } };
  • 17. 17 int main() { cout <<“nnEnter Mainn”; alpha A1, A2, A3, A4; { cout <<“nnEnter Block1n”; alpha A5; } { cout <<“nnEnter Block2n”; alpha A6; } cout <<“nnRe-enter Mainn”; return 0; }
  • 18. 18 Enter Main No of object created 1 No of object created 2 No of object created 3 No of object created 4 Enter Block1 No of object created 5 No of object destroyed 5 Enter Block2 No of object created 5 No of object destroyed 5 Re-enter Main No of object destroyed 4 No of object destroyed 3 No of object destroyed 2 No of object destroyed 1