SlideShare a Scribd company logo
CONSTRUCTORS
AND
DESTRUCTORS
CONSTRUCTORS
A member function with the same as its class is called Constructor and it is used to
initialize the object of that class with a legal initial value.
Example :
class student
{
private:
int rollno;
float marks;
public:
student( ) //Constructor
{ rollno=0; marks=0.0; }
};
CONSTRUCTOR CALLING
A constructor can be called in two ways: implicitly and explicitly.
class student
{
private:
int rollno;
float marks;
public:
student( ) //Constructor
{ rollno=0; marks=0.0; }
};
void main()
{
student s1; //implicit call
}
class student
{
private:
int rollno;
float marks;
public:
student( ) //Constructor
{ rollno=0; marks=0.0; }
};
void main()
{
student s1 = student(); //explicit call
}
IMPLICIT CALL OF CONSTRUCTOR EXPLICIT CALL OF CONSTRUCTOR
FEATURES OF CONSTRUCTORS
 Constructor has the same name as class.
 Constructor does not have any return type not even void.
 Constructor can be declared only in the public section of the class.
 Constructor is called automatically when the object of the class is
created.
TYPES OF CONSTRUCTOR
1. Default Constructor: A constructor that accepts no parameter is called the Default
Constructor.
2. Parameterized Constructor: A constructor that accepts parameters for its invocation is
known as parameterized Constructor, also called as Regular Constructor.
3. Copy Constructor: A copy constructor is a special constructor in the C++ programming
language used to create a new object as a copy of an existing object.
Example :
class student
{
private:
int rollno;
float marks;
public:
student( ) // Default Constructor
{ rollno=0; marks=0.0; }
void display();
void enter();
};
void main()
{
student s1; // default constructor called
}
DEFAULT CONSTRUCTOR
Default constructor takes no argument.
It is used to initialize an object of a class with legal initial values.
PARAMETRISED CONSTRUCTOR
 Parametrized constructor accepts
arguments.
 It initializes the data members of
the object with the arguments
passed to it.
 When the object s1 is created,
default constructor is called and
when the objects s2 is created,
parametrized constructor is called
and this is implicit call of
parametrized constructor.
 When the object s3 is created,
again the parametrized
constructor is called but this
explicit call of parametrized
constructor.
class student
{
private:
int rollno;
char name[20];
float marks;
public:
student( )
// Default Constructor
{ rollno=0; marks=0.0; }
student(int roll, char nam[20],
float mar)
// Parametrized Constructor
{ rollno=roll;
strcpy(name, nam);
marks =mar;
}
void display();
void enter();
};
void main()
{
student s1;
student s2(1, “RAMESH”,
350);
student s3=student(2,
”KAJAL”, 400);
}
COPY CONSTRUCTOR
 Copy constructor accepts an object as an argument.
 It creates a new object and initializes its data members with data members of the object passed
to it as an argument.
Syntax : class_name( class_name & object_name)
{
}
Note: It is necessary to pass an object by reference in copy constructor because if do not pass the
object by reference then a copy constructor will be invoked to make the copy of the object.
In this process copy constructor will be invoked again and it will be a recursive process ie this
process will repeat again and again endlessly resulting in running short of memory. Ultimately our
system will hang.
COPY CONSTRUCTOR EXAMPLE
Example :
Statement1: default
constructor is called.
Statement2: parametrized
constructor is called.
Statement 3: copy
constructor is called.
Statement4: Parametrized
constructor is called.
statement5: Copy
constructor is called.
class student
{
private:
int rollno;
char name[20];
float marks;
public:
student( )
// Default Constructor
{ rollno=0; marks=0.0; }
student(int roll, char nam[20],
float mar)
// Parametrized Constructor
{ rollno=roll;
strcpy(name, nam);
marks =mar; }
student( student & s) // Copy
Constructor
{ rollno= s.rollno;
strcpy(name, s.name);
marks =s.marks;
}
}
void main()
{
student s1; //statement1
student s2( 1, “RAJESH”, 450); //
statemet2
student s3(s2); //statement3
student s4(2, “MOHIT”,320);
//statement4
student s5=s4; //statement5
}
COPY CONSTRUCTOR INVOCATION
Case 1: When an object is passed by value to a function: The pass by value method requires a
copy of the passed argument to be created for the function to operate upon. Thus to create the copy
of the passed object, copy constructor is invoked. Example:
Explanation:
As we are passing the
object s6 by value so
when the function call
job is invoked a copy of
stu is created and values
of object s6 are copied to
object stu.
class student
{
private:
int rollno;
char name[20];
float marks;
public:
student( ) // Default Constructor
{ rollno=0; marks=0.0; }
student(int roll, char nam[20],
float mar) //Parametrized
{ rollno=roll;
strcpy(name, nam);
marks =mar; }
student( student & s) // Copy
Constructor
{ rollno= s.rollno;
strcpy(name, s.name);
marks =s.marks;
}
}
void job( student stu)
{ }
void main( )
{
student s6(6, “KAPIL”, 245);
job(s6);
}
COPY CONSTRUCTOR INVOCATION Contd…..
Case 2: When a function returns an object : When an object is returned by a function the copy
constructor is invoked.
Explanation:
 When the function job is
invoked it creates a
temporary object t1 and
then returns it.
 At that time the copy
constructor is invoked to
create a copy of the object
t1 returned by job() and its
value is assigned to s7.
 The copy constructor
creates a temporary object
to hold the return value of
a function returning an
object.
class student
{
private:
int rollno;
char name[20];
float marks;
public:
student( ) // Default
{ rollno=0; marks=0.0; }
student(int roll, char nam[20],
float mar) // Parametrised
{ rollno=roll;
strcpy(name, nam);
marks =mar;
}
student( student & s) // Copy
Constructor
{ rollno= s.rollno;
strcpy(name, s.name);
marks =s.marks;
}
}
student job( )
{ student t1(12, “AJAY”, 443);
return t1; }
void main( )
{
student s6(6, “KAPIL”, 245);
student s7=job();
}
COPY CONSTRUCTOR INVOCATION Contd…..
Case 3: Copy constructor is invoked when the value of one object is copied to another object at the
time of creating an object. In all the other cases copy constructor is not invoked and value of one
object is copied to another object simply data member by data member. Example :
EXPLANATION:
Statement1: default
constructor is called
Statement2: parametrized
constructor is called
Statement 3: copy
constructor is called
statement4: Parametrized
constructor is called
statement5: Copy
constructor is called
statement6: Copy
constructor is not called
class student
{
private:
int rollno;
char name[20];
float marks;
public:
student( ) // Default Constructor
{ rollno=0; marks=0.0; }
student(int roll, char nam[20], float
mar) // Parametrized Constructor
{ rollno=roll;
strcpy(name, nam);
marks =mar;
}
student( student & s) // Copy
Constructor
{ rollno= s.rollno;
strcpy(name, s.name);
marks =s.marks;
} }
void main()
{
student s1; //statement1
student s2( 1, “RAJESH”, 450); //
statemet2
student s3(s2); //statement3
student s4(2, “MOHIT”,320);
//statement4
Student s5=s4; //statement5
s1=s5; } // statement6
CONSTRUCTOR OVERLOADING
C++ allows more than one constructors to be defined in a single class.
Defining more than one constructors in a single class provided they all differ in either type or
number of argument is called constructor overloading.
 In the class student, there are 4
constructors:
1 default constructor,
2 parametrized constructors
and 1 copy constructor.
 Defining more than one
constructor in a single class is
called constructor overloading.
 We can define as many
parametrized constructors as
we want in a single class
provided they all differ in either
number or type of arguments.
class student
{
private:
int rollno;
char name[20];
float marks;
public:
student( ) // Default Constructor
{ rollno=0; marks=0.0; }
student(int roll, char nam[20],
float mar) // Parametrized Constructor
{ rollno=roll;
strcpy(name, nam);
marks =mar;
}
student(int roll, char nam[20]) //
Parametrized Constructor
{ rollno=roll;
strcpy(name, nam);
marks =100;
}
student( student & s) // Copy
Constructor
{ rollno= s.rollno;
strcpy(name, s.name);
marks =s.marks;
}
}
DESTRUCTOR
 A destructor is a member function whose
name is the same as the class name and
is preceded by tilde(“~”).
 It is automatically by the compiler when
an object goes out of scope.
 Destructors are usually used to deallocate
memory and do other cleanup for a class
object and its class members when the
object is destroyed.
 Note: In this program first the object s1 is
created. At that time constructor is called.
When the program goes over the object
s1 will also go out of scope. At that time
destructor is called.
Example :
class student
{ private:
int rollno;
float marks;
public:
student( ) //Constructor
{ rollno=0; marks=0.0; }
~student() //Destructor
{ }
};
void main()
{ student s1;}
FEATURES OF DESTRUCTOR
It has the same name as that of the class and preceded by tilde sign(~).
It is automatically by the compiler when an object goes out of scope.
Destructors are usually used to deallocate memory and do other cleanup for
a class object and its class members when the object goes out of scope.
Destructor is always declared in the public section of the class.
We can have only one destructor in a class.
POINTS TO REMEMBER
Constructors and destructors do not have return type, not even void nor can they
return values.
The compiler automatically calls constructors when defining class objects and
calls destructors when class objects go out of scope.
Derived classes do not inherit constructors or destructors from their base
classes, but they do call the constructor and destructor of base classes.
The constructor of the base class is called first and then the constructor of the
child class/es.
The destructor for a child class object is called before destructors for base
class/es are called.
If we do not declare our own constructor and destructor in the class, then they
are automatically defined by the compiler.
POINTS TO REMEMBER Contd……
 I f we declare our own constructor of any one type then it is necessary to define constructors
of other types also otherwise we will not be able to create an object whose constructor
definition is not given in the class.
 C++ compiler uses the concept of stack in memory allocation and deallocation. Thus
compiler creates the memory in sequential order and delete the memory in reverse order.
Deallocation
Allocation
x3
x2 x1
Consider the class student declared in the previous slides. If the main
program is as given below then allocation and deallocation of
memory to objects will take place as given in the figure::
void main()
{
student x1, x2, x3;
}
x1
x2
x3
EXAMPLE EXPLAINED
OUTPUT
Default constructor called
Parametrized constructor
called
Copy constructor called
Parametrized constructor
called
Copy constructor called
Destructor called
Destructor called
Destructor called
Destructor called
Destructor called
class student
{
private:
int rollno;
char name[20];
float marks;
public:
student( ) // Default Constructor
{ rollno=0; marks=0.0;
cout<<“Default constructor calledn”; }
student(int roll, char nam[20], float mar)
// Parametrized Constructor
{ rollno=roll;
strcpy(name, nam);
marks =mar;
cout<<“Parametrized constructor
calledn”;
}
student( student & s) // Copy
Constructor
{ rollno= s.rollno;
strcpy(name, s.name);
marks =s.marks;
cout<<“copy constructor
calledn”;
}
~student() //Destructor
{ cout<<“Destructor
calledn”; }
}
void main()
{
student s1;
student s2( 1, “RAJESH”, 450);
student s3(s2);
student s4(2, “MOHIT”,320);
student s5=s4; }

More Related Content

What's hot

Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).pptAlok Kumar
 
[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers
Muhammad Hammad Waseem
 
This pointer
This pointerThis pointer
This pointer
Kamal Acharya
 
Function C programming
Function C programmingFunction C programming
Function C programming
Appili Vamsi Krishna
 
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCECLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
Venugopalavarma Raja
 
Encapsulation C++
Encapsulation C++Encapsulation C++
Encapsulation C++
Hashim Hashim
 
Union in C programming
Union in C programmingUnion in C programming
Union in C programming
Kamal Acharya
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
Prof. Dr. K. Adisesha
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
Sujith Kumar
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Vineeta Garg
 
Friend function
Friend functionFriend function
Friend function
zindadili
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
sai tarlekar
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
TMARAGATHAM
 
Constructor and Types of Constructors
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of Constructors
Dhrumil Panchal
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Vishal Patil
 
Lecture19 unionsin c.ppt
Lecture19 unionsin c.pptLecture19 unionsin c.ppt
Lecture19 unionsin c.ppteShikshak
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and DestructorKamal Acharya
 
Array of objects.pptx
Array of objects.pptxArray of objects.pptx
Array of objects.pptx
RAGAVIC2
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
HalaiHansaika
 

What's hot (20)

Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 
[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers
 
This pointer
This pointerThis pointer
This pointer
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCECLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
 
Encapsulation C++
Encapsulation C++Encapsulation C++
Encapsulation C++
 
Union in C programming
Union in C programmingUnion in C programming
Union in C programming
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Friend function
Friend functionFriend function
Friend function
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 
Constructor and Types of Constructors
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of Constructors
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Lecture19 unionsin c.ppt
Lecture19 unionsin c.pptLecture19 unionsin c.ppt
Lecture19 unionsin c.ppt
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
Array of objects.pptx
Array of objects.pptxArray of objects.pptx
Array of objects.pptx
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 

Viewers also liked

Structured query language functions
Structured query language functionsStructured query language functions
Structured query language functions
Vineeta Garg
 
Classes and objects1
Classes and objects1Classes and objects1
Classes and objects1
Vineeta Garg
 
Advanced data structures using c++ 3
Advanced data structures using c++ 3Advanced data structures using c++ 3
Advanced data structures using c++ 3Shaili Choudhary
 
Structured query language constraints
Structured query language constraintsStructured query language constraints
Structured query language constraints
Vineeta Garg
 
13. Indexing MTrees - Data Structures using C++ by Varsha Patil
13. Indexing MTrees - Data Structures using C++ by Varsha Patil13. Indexing MTrees - Data Structures using C++ by Varsha Patil
13. Indexing MTrees - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. Patil
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. PatilDiscrete Mathematics S. Lipschutz, M. Lipson And V. H. Patil
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. Patil
widespreadpromotion
 
Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++
Vineeta Garg
 
Working with Cookies in NodeJS
Working with Cookies in NodeJSWorking with Cookies in NodeJS
Working with Cookies in NodeJS
Jay Dihenkar
 
Data types in c++
Data types in c++Data types in c++
Data types in c++
Venkata.Manish Reddy
 
16. Algo analysis & Design - Data Structures using C++ by Varsha Patil
16. Algo analysis & Design - Data Structures using C++ by Varsha Patil16. Algo analysis & Design - Data Structures using C++ by Varsha Patil
16. Algo analysis & Design - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
Data Structure
Data StructureData Structure
Data Structuresheraz1
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
Vineeta Garg
 
10. Search Tree - Data Structures using C++ by Varsha Patil
10. Search Tree - Data Structures using C++ by Varsha Patil10. Search Tree - Data Structures using C++ by Varsha Patil
10. Search Tree - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
Stacks in algorithems & data structure
Stacks in algorithems & data structureStacks in algorithems & data structure
Stacks in algorithems & data structure
faran nawaz
 
stacks in algorithems and data structure
stacks in algorithems and data structurestacks in algorithems and data structure
stacks in algorithems and data structure
faran nawaz
 
Queues in C++
Queues in C++Queues in C++
Queues in C++
Vineeta Garg
 
Structure of C++ - R.D.Sivakumar
Structure of C++ - R.D.SivakumarStructure of C++ - R.D.Sivakumar
Structure of C++ - R.D.Sivakumar
Sivakumar R D .
 
11. Hashing - Data Structures using C++ by Varsha Patil
11. Hashing - Data Structures using C++ by Varsha Patil11. Hashing - Data Structures using C++ by Varsha Patil
11. Hashing - Data Structures using C++ by Varsha Patil
widespreadpromotion
 

Viewers also liked (20)

Structured query language functions
Structured query language functionsStructured query language functions
Structured query language functions
 
Classes and objects1
Classes and objects1Classes and objects1
Classes and objects1
 
Advanced data structures using c++ 3
Advanced data structures using c++ 3Advanced data structures using c++ 3
Advanced data structures using c++ 3
 
Structured query language constraints
Structured query language constraintsStructured query language constraints
Structured query language constraints
 
13. Indexing MTrees - Data Structures using C++ by Varsha Patil
13. Indexing MTrees - Data Structures using C++ by Varsha Patil13. Indexing MTrees - Data Structures using C++ by Varsha Patil
13. Indexing MTrees - Data Structures using C++ by Varsha Patil
 
Pp
PpPp
Pp
 
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. Patil
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. PatilDiscrete Mathematics S. Lipschutz, M. Lipson And V. H. Patil
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. Patil
 
Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++
 
Working with Cookies in NodeJS
Working with Cookies in NodeJSWorking with Cookies in NodeJS
Working with Cookies in NodeJS
 
Data types in c++
Data types in c++Data types in c++
Data types in c++
 
16. Algo analysis & Design - Data Structures using C++ by Varsha Patil
16. Algo analysis & Design - Data Structures using C++ by Varsha Patil16. Algo analysis & Design - Data Structures using C++ by Varsha Patil
16. Algo analysis & Design - Data Structures using C++ by Varsha Patil
 
C++ data types
C++ data typesC++ data types
C++ data types
 
Data Structure
Data StructureData Structure
Data Structure
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
 
10. Search Tree - Data Structures using C++ by Varsha Patil
10. Search Tree - Data Structures using C++ by Varsha Patil10. Search Tree - Data Structures using C++ by Varsha Patil
10. Search Tree - Data Structures using C++ by Varsha Patil
 
Stacks in algorithems & data structure
Stacks in algorithems & data structureStacks in algorithems & data structure
Stacks in algorithems & data structure
 
stacks in algorithems and data structure
stacks in algorithems and data structurestacks in algorithems and data structure
stacks in algorithems and data structure
 
Queues in C++
Queues in C++Queues in C++
Queues in C++
 
Structure of C++ - R.D.Sivakumar
Structure of C++ - R.D.SivakumarStructure of C++ - R.D.Sivakumar
Structure of C++ - R.D.Sivakumar
 
11. Hashing - Data Structures using C++ by Varsha Patil
11. Hashing - Data Structures using C++ by Varsha Patil11. Hashing - Data Structures using C++ by Varsha Patil
11. Hashing - Data Structures using C++ by Varsha Patil
 

Similar to Constructors and destructors

Constructors & Destructors
Constructors  & DestructorsConstructors  & Destructors
Constructors & Destructors
Rokonuzzaman Rony
 
C++Constructors
C++ConstructorsC++Constructors
C++Constructors
Nusrat Gulbarga
 
Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)
Abu Saleh
 
C++ basic
C++ basicC++ basic
C++ basic
TITTanmoy
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
Venugopalavarma Raja
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
Epsiba1
 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objects
Rai University
 
chapter-9-constructors.pdf
chapter-9-constructors.pdfchapter-9-constructors.pdf
chapter-9-constructors.pdf
study material
 
Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objects
Rai University
 
Constructor and desturctor
Constructor and desturctorConstructor and desturctor
Constructor and desturctorSomnath Kulkarni
 
Class and object
Class and objectClass and object
Class and object
prabhat kumar
 
5 Constructors and Destructors
5 Constructors and Destructors5 Constructors and Destructors
5 Constructors and Destructors
Praveen M Jigajinni
 
Chapter19 constructor-and-destructor
Chapter19 constructor-and-destructorChapter19 constructor-and-destructor
Chapter19 constructor-and-destructorDeepak Singh
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
Keyur Vadodariya
 
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptxObject Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
RashidFaridChishti
 
Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptx
Rassjb
 
Object & classes
Object & classes Object & classes
Object & classes
Paresh Parmar
 
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxCONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
DeepasCSE
 
constructors and destructors
constructors and destructorsconstructors and destructors
constructors and destructors
Akshaya Parida
 

Similar to Constructors and destructors (20)

Constructors & Destructors
Constructors  & DestructorsConstructors  & Destructors
Constructors & Destructors
 
C++Constructors
C++ConstructorsC++Constructors
C++Constructors
 
Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)
 
C++ basic
C++ basicC++ basic
C++ basic
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objects
 
chapter-9-constructors.pdf
chapter-9-constructors.pdfchapter-9-constructors.pdf
chapter-9-constructors.pdf
 
Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objects
 
Constructor and desturctor
Constructor and desturctorConstructor and desturctor
Constructor and desturctor
 
Class and object
Class and objectClass and object
Class and object
 
5 Constructors and Destructors
5 Constructors and Destructors5 Constructors and Destructors
5 Constructors and Destructors
 
Chapter19 constructor-and-destructor
Chapter19 constructor-and-destructorChapter19 constructor-and-destructor
Chapter19 constructor-and-destructor
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptxObject Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
 
Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptx
 
Object & classes
Object & classes Object & classes
Object & classes
 
Java basic understand OOP
Java basic understand OOPJava basic understand OOP
Java basic understand OOP
 
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxCONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
 
constructors and destructors
constructors and destructorsconstructors and destructors
constructors and destructors
 

Recently uploaded

The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
deeptiverma2406
 
JEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questionsJEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questions
ShivajiThube2
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
Wasim Ak
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Multithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race conditionMultithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race condition
Mohammed Sikander
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
David Douglas School District
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 

Recently uploaded (20)

The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
 
JEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questionsJEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questions
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Multithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race conditionMultithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race condition
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 

Constructors and destructors

  • 2. CONSTRUCTORS A member function with the same as its class is called Constructor and it is used to initialize the object of that class with a legal initial value. Example : class student { private: int rollno; float marks; public: student( ) //Constructor { rollno=0; marks=0.0; } };
  • 3. CONSTRUCTOR CALLING A constructor can be called in two ways: implicitly and explicitly. class student { private: int rollno; float marks; public: student( ) //Constructor { rollno=0; marks=0.0; } }; void main() { student s1; //implicit call } class student { private: int rollno; float marks; public: student( ) //Constructor { rollno=0; marks=0.0; } }; void main() { student s1 = student(); //explicit call } IMPLICIT CALL OF CONSTRUCTOR EXPLICIT CALL OF CONSTRUCTOR
  • 4. FEATURES OF CONSTRUCTORS  Constructor has the same name as class.  Constructor does not have any return type not even void.  Constructor can be declared only in the public section of the class.  Constructor is called automatically when the object of the class is created.
  • 5. TYPES OF CONSTRUCTOR 1. Default Constructor: A constructor that accepts no parameter is called the Default Constructor. 2. Parameterized Constructor: A constructor that accepts parameters for its invocation is known as parameterized Constructor, also called as Regular Constructor. 3. Copy Constructor: A copy constructor is a special constructor in the C++ programming language used to create a new object as a copy of an existing object.
  • 6. Example : class student { private: int rollno; float marks; public: student( ) // Default Constructor { rollno=0; marks=0.0; } void display(); void enter(); }; void main() { student s1; // default constructor called } DEFAULT CONSTRUCTOR Default constructor takes no argument. It is used to initialize an object of a class with legal initial values.
  • 7. PARAMETRISED CONSTRUCTOR  Parametrized constructor accepts arguments.  It initializes the data members of the object with the arguments passed to it.  When the object s1 is created, default constructor is called and when the objects s2 is created, parametrized constructor is called and this is implicit call of parametrized constructor.  When the object s3 is created, again the parametrized constructor is called but this explicit call of parametrized constructor. class student { private: int rollno; char name[20]; float marks; public: student( ) // Default Constructor { rollno=0; marks=0.0; } student(int roll, char nam[20], float mar) // Parametrized Constructor { rollno=roll; strcpy(name, nam); marks =mar; } void display(); void enter(); }; void main() { student s1; student s2(1, “RAMESH”, 350); student s3=student(2, ”KAJAL”, 400); }
  • 8. COPY CONSTRUCTOR  Copy constructor accepts an object as an argument.  It creates a new object and initializes its data members with data members of the object passed to it as an argument. Syntax : class_name( class_name & object_name) { } Note: It is necessary to pass an object by reference in copy constructor because if do not pass the object by reference then a copy constructor will be invoked to make the copy of the object. In this process copy constructor will be invoked again and it will be a recursive process ie this process will repeat again and again endlessly resulting in running short of memory. Ultimately our system will hang.
  • 9. COPY CONSTRUCTOR EXAMPLE Example : Statement1: default constructor is called. Statement2: parametrized constructor is called. Statement 3: copy constructor is called. Statement4: Parametrized constructor is called. statement5: Copy constructor is called. class student { private: int rollno; char name[20]; float marks; public: student( ) // Default Constructor { rollno=0; marks=0.0; } student(int roll, char nam[20], float mar) // Parametrized Constructor { rollno=roll; strcpy(name, nam); marks =mar; } student( student & s) // Copy Constructor { rollno= s.rollno; strcpy(name, s.name); marks =s.marks; } } void main() { student s1; //statement1 student s2( 1, “RAJESH”, 450); // statemet2 student s3(s2); //statement3 student s4(2, “MOHIT”,320); //statement4 student s5=s4; //statement5 }
  • 10. COPY CONSTRUCTOR INVOCATION Case 1: When an object is passed by value to a function: The pass by value method requires a copy of the passed argument to be created for the function to operate upon. Thus to create the copy of the passed object, copy constructor is invoked. Example: Explanation: As we are passing the object s6 by value so when the function call job is invoked a copy of stu is created and values of object s6 are copied to object stu. class student { private: int rollno; char name[20]; float marks; public: student( ) // Default Constructor { rollno=0; marks=0.0; } student(int roll, char nam[20], float mar) //Parametrized { rollno=roll; strcpy(name, nam); marks =mar; } student( student & s) // Copy Constructor { rollno= s.rollno; strcpy(name, s.name); marks =s.marks; } } void job( student stu) { } void main( ) { student s6(6, “KAPIL”, 245); job(s6); }
  • 11. COPY CONSTRUCTOR INVOCATION Contd….. Case 2: When a function returns an object : When an object is returned by a function the copy constructor is invoked. Explanation:  When the function job is invoked it creates a temporary object t1 and then returns it.  At that time the copy constructor is invoked to create a copy of the object t1 returned by job() and its value is assigned to s7.  The copy constructor creates a temporary object to hold the return value of a function returning an object. class student { private: int rollno; char name[20]; float marks; public: student( ) // Default { rollno=0; marks=0.0; } student(int roll, char nam[20], float mar) // Parametrised { rollno=roll; strcpy(name, nam); marks =mar; } student( student & s) // Copy Constructor { rollno= s.rollno; strcpy(name, s.name); marks =s.marks; } } student job( ) { student t1(12, “AJAY”, 443); return t1; } void main( ) { student s6(6, “KAPIL”, 245); student s7=job(); }
  • 12. COPY CONSTRUCTOR INVOCATION Contd….. Case 3: Copy constructor is invoked when the value of one object is copied to another object at the time of creating an object. In all the other cases copy constructor is not invoked and value of one object is copied to another object simply data member by data member. Example : EXPLANATION: Statement1: default constructor is called Statement2: parametrized constructor is called Statement 3: copy constructor is called statement4: Parametrized constructor is called statement5: Copy constructor is called statement6: Copy constructor is not called class student { private: int rollno; char name[20]; float marks; public: student( ) // Default Constructor { rollno=0; marks=0.0; } student(int roll, char nam[20], float mar) // Parametrized Constructor { rollno=roll; strcpy(name, nam); marks =mar; } student( student & s) // Copy Constructor { rollno= s.rollno; strcpy(name, s.name); marks =s.marks; } } void main() { student s1; //statement1 student s2( 1, “RAJESH”, 450); // statemet2 student s3(s2); //statement3 student s4(2, “MOHIT”,320); //statement4 Student s5=s4; //statement5 s1=s5; } // statement6
  • 13. CONSTRUCTOR OVERLOADING C++ allows more than one constructors to be defined in a single class. Defining more than one constructors in a single class provided they all differ in either type or number of argument is called constructor overloading.  In the class student, there are 4 constructors: 1 default constructor, 2 parametrized constructors and 1 copy constructor.  Defining more than one constructor in a single class is called constructor overloading.  We can define as many parametrized constructors as we want in a single class provided they all differ in either number or type of arguments. class student { private: int rollno; char name[20]; float marks; public: student( ) // Default Constructor { rollno=0; marks=0.0; } student(int roll, char nam[20], float mar) // Parametrized Constructor { rollno=roll; strcpy(name, nam); marks =mar; } student(int roll, char nam[20]) // Parametrized Constructor { rollno=roll; strcpy(name, nam); marks =100; } student( student & s) // Copy Constructor { rollno= s.rollno; strcpy(name, s.name); marks =s.marks; } }
  • 14. DESTRUCTOR  A destructor is a member function whose name is the same as the class name and is preceded by tilde(“~”).  It is automatically by the compiler when an object goes out of scope.  Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed.  Note: In this program first the object s1 is created. At that time constructor is called. When the program goes over the object s1 will also go out of scope. At that time destructor is called. Example : class student { private: int rollno; float marks; public: student( ) //Constructor { rollno=0; marks=0.0; } ~student() //Destructor { } }; void main() { student s1;}
  • 15. FEATURES OF DESTRUCTOR It has the same name as that of the class and preceded by tilde sign(~). It is automatically by the compiler when an object goes out of scope. Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object goes out of scope. Destructor is always declared in the public section of the class. We can have only one destructor in a class.
  • 16. POINTS TO REMEMBER Constructors and destructors do not have return type, not even void nor can they return values. The compiler automatically calls constructors when defining class objects and calls destructors when class objects go out of scope. Derived classes do not inherit constructors or destructors from their base classes, but they do call the constructor and destructor of base classes. The constructor of the base class is called first and then the constructor of the child class/es. The destructor for a child class object is called before destructors for base class/es are called. If we do not declare our own constructor and destructor in the class, then they are automatically defined by the compiler.
  • 17. POINTS TO REMEMBER Contd……  I f we declare our own constructor of any one type then it is necessary to define constructors of other types also otherwise we will not be able to create an object whose constructor definition is not given in the class.  C++ compiler uses the concept of stack in memory allocation and deallocation. Thus compiler creates the memory in sequential order and delete the memory in reverse order. Deallocation Allocation x3 x2 x1 Consider the class student declared in the previous slides. If the main program is as given below then allocation and deallocation of memory to objects will take place as given in the figure:: void main() { student x1, x2, x3; } x1 x2 x3
  • 18. EXAMPLE EXPLAINED OUTPUT Default constructor called Parametrized constructor called Copy constructor called Parametrized constructor called Copy constructor called Destructor called Destructor called Destructor called Destructor called Destructor called class student { private: int rollno; char name[20]; float marks; public: student( ) // Default Constructor { rollno=0; marks=0.0; cout<<“Default constructor calledn”; } student(int roll, char nam[20], float mar) // Parametrized Constructor { rollno=roll; strcpy(name, nam); marks =mar; cout<<“Parametrized constructor calledn”; } student( student & s) // Copy Constructor { rollno= s.rollno; strcpy(name, s.name); marks =s.marks; cout<<“copy constructor calledn”; } ~student() //Destructor { cout<<“Destructor calledn”; } } void main() { student s1; student s2( 1, “RAJESH”, 450); student s3(s2); student s4(2, “MOHIT”,320); student s5=s4; }