SlideShare a Scribd company logo
Constructors & Destructors
Constructors
A special member function having same
name as that of its class which is used to
initialize some valid values to the
member variables.
Key points while defining constructor
A constructor has same name as that of the class to
which it belongs.
 A constructor is executed automatically whenever
the object is created
A constructor doesn`t have a return type, not even
void
 We can declare more than one constructor in a class.
These constructor differ in there parameter list.
If you don’t provide a constructor of your own then
the compiler generates a default constructor
(expects no parameters and has an empty
body).
A constructor can preferably be used for
initialization and not for inputoutput operations.
• They can’t be inherited; through a derived class,
can call the base class constructor.
• Like other C++ functions, they can have default
arguments.
• Constructors can’t be virtual.
• Constructors can be inside the class definition or
outside the class definition.
• Constructor can’t be friend function.
• They can’t be used in union.
Contd..
• Constructor should be declared in the public section
of the class. If it is not declared in public section of
the class then the whole class become private . By
doing this the object of the class created from
outside cannot invoke the constructor which is the
first member function to be executed
automatically.
Syntax
class CLASSNAME
{
public:
CLASSNAME([parameter list]);
};
Example
#include<iostream.h>
#include<conio.h>
class Rectangle
{
private:
int length,breadth;
public:
Rectangle()
{
length=5,breadth=6;
}
void area()
{
int a=(length*breadth);
cout<<"area is"<<a;
}
};
void main()
{
clrscr();
Rectangle r1;
r1.area();
getch();
}
TYPES OF CONSTRUCTOR
• 1.Default Constructor
• 2.Parameterized Constructor
• 3.Copy Constructor
Parameterized Constructor
In order to initialize various data elements of
different objects with different values when they
are created. C++ permits us to achieve this objects
by passing argument to the constructor function
when the object are created . The constructor that
can take arguments are called parameterized
constructors
class abc
{
int m, n;
public:
abc (int x, int y); // parameterized constructor
................
.................
};
abc : : abc (int x, int y)
{
m = x;
n = y;
}
Parameterized constructor
#include<iostream.h>
#include<conio.h>
class Rectangle
{
private:
int length,breadth;
public:
Rectangle(int a,int b)
{
length=a;
breadth=b;
}
void area()
{
int a=(length*breadth);
cout<<"area is="<<a;
}
};
void main()
{
Rectangle r1(5,6);
Rectangle r2(7,8);
clrscr();
r1.area();cout<<endl;
r2.area();
getch();
}
Copy constructor
• A copy constructor is a constructor that creates a
new object using an existing object of the same
class.
• and initializes each data member of newly created
object with corresponding data member of existing
object passed as argumnt.
• since it creates a copy of an existing object so it is
called copy constructor.
Example
class counter
{
Int c;
public:
Counter(int a) //single parameter constructor
{
c=a;
}
counter(counter &ob) //copy constructor
{
cout<<“copy constructor invoked”;
c=ob.c;
}
}
void show()
{
cout<<c;
}
};
void main()
{
clrscr();
counter C1(10);
counter C2(C1);// call copy constructor
C1.show();
C2.show();
getch();
}
Another example of copy constructor
#include<iostream>
#include<conio.h>
using namespace std;
class Point
{
private:
int x, y;
public:
Point(int x1, int y1)
{
x = x1;
y = y1;
}
// Copy constructor
Point(const Point &p2)
{
x = p2.x;
y = p2.y;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
};
int main()
{
Point p1(10, 15); // Normal constructor is called here
Point p2 = p1; // Copy constructor is called here
// Let us access values assigned by constructors
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout << "np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
return 0;
}
class code
{
int id;
public:
code() { }
code(int a)
{
id = a;
}
code (code & x)
{
id = x. id;
}
void display()
{ cout<<id;
} };
int main()
{
code A(100);
code B(A);
code C = A;
code D;
D = A;
A.display();
B.display();
C.display();
D.display();
getch();
return 0;
}
Destructors
Is a member function having same name
as that of constructor but it is preceded
by a tilde(~) symbol and is executed
automatically when object of a class is
destroyed
Key points while defining destructor
• A destructor has same name as that of the class to which it belongs
preceded by tilde(~)sign.
• A destructor is executed automatically whenever the object is destroyed.
• A destructor doesn`t have a return type, not even void and no arguments
• There is only one destructor in class .
• If you don’t provide a destructor of your own then the compiler generates a
default destructor
• A destructor can be used to deallocate memory for an object and declared
in the public section.
Need for Destructors
• To de-initialize the objects when they are destroyed
• To clear memory space occupied by a data
member.
syntax
class CLASSNAME
{
……………….
public:
~CLASSNAME([parameter list]);
};
Note
• Execute the program in Turbo c++.
• To see the output, press Alt+F5
Program on destructor
Class sample
{
Public:
Sample
{
Cout<<“object born”<<endl;
}
Public:
{
~sample
{
Cout<<object dies<<endl;
}
};
int main()
{
sample s;
Cout<<“main terminated”<<endl;
getch();
return 0;
}
Example
#include<iostream.h>
#include<conio.h>
class counter
{
int id;
public:
counter(int i)
{
id=i;
cout<<“contructor of object with id=”<<id;
~counter()
{
cout<<“destructor with id=”<<id;
}
};
void main()
{
counter c1(1);
counter c2(2);
counter c3(3);
cout<<“n end of main”;
getch();
}
• Output
constructor of object with id=1
constructor of object with id=2
constructor of object with id=3
End of main
destructor with id=3
destructor with id=2
destructor with id=1
Note ::Destructor Always deallocate memory in reverse order.
1 Statically allocated object for class A in C++ is
A *obj = new A();
A obj;
A obj = new A();
None
When you create an object of a class A like A obj ;
then which one will be called automatically
A Constructor
B Destructor
C Copy constructor
D Assignment operator
3 Data members and member functions of a class in
C++ program are by default
protected
public
private
None
4 Which operator is used to allocate an object
dynamically of a class in C++?
Scope resolution operator
Conditional operator
New operator
Membership access
The static member functions __________________
a) Have access to all the members of a class
b) Have access to only constant members of a class
c.) Have access to only the static members of a class
d) Have direct access to all other class members also
The static member functions ____________________
a.) Can be called using class name
b) Can be called using program name
c) Can be called directly
d) Can’t be called outside the function
Which among the following is true?
a) Static member functions can be overloaded
b.) Static member functions can’t be overloaded
c) Static member functions can be overloaded using
derived classes
d) Static member functions are implicitly overloaded
Which keyword should be used to declare the static
member functions?
a.) static
b) stat
c) const
d) common
Assume class TEST. Which of the following statements
is/are responsible to invoke copy constructor?
a. TEST T2(T1)
b. TEST T4 = T1
c. T2 = T1
D). both a and b
Which of the following statements are not true about
destructor?
1. It is invoked when object goes out of the scope
2. Like constructor, it can also have parameters
3. It can be virtual
4. It can be declared in private section
5. It bears same name as that of the class and precedes Lambda
sign.
a. Only 2, 3, 5
b. Only 2, 3, 4
c). Only 2, 4, 5
d. Only 3, 4, 5
A Constructor that does not have any parameters is
called____________ Constructor.
a. Custom
b. Dynamic
c. Static
d). Default
Which of the followings are true about constructors?
1. A class can have more than one constructor.
2. They can be inherited.
3. Their address can be referred.
4. Constructors cannot be declared in protected section of the class.
5. Constructors cannot return values.
a. Only 1,2,4
b. 1,2,4,5
c. 1,3,5
d.) 1,4,5
In a program, If there exists a function template with
two parameters and normal function say void add(int
, int), so add(3,4) will _____________________ .
a. Invoke function template body as it is generic one
b.) Invokes normal function as it exactly matches
with its prototype
c. Not be called and Compiler issues warning
d. Not be called and Compiler issues ambiguity in
calling add()

More Related Content

PPTX
Destructors
PPTX
Types of function call
PPTX
Exception Handling in object oriented programming using C++
PPTX
Constructor and Destructor in c++
PPTX
PDF
Constructors and Destructors
PPTX
Constructors in C++
PPTX
constructors and destructors in c++
Destructors
Types of function call
Exception Handling in object oriented programming using C++
Constructor and Destructor in c++
Constructors and Destructors
Constructors in C++
constructors and destructors in c++

What's hot (20)

PPT
Constructor
PPTX
Functions in c++
PPT
Strings
PPTX
Function in c program
PPT
Cascading Style Sheets
PDF
Memory Management C++ (Peeling operator new() and delete())
PPTX
classes and objects in C++
PPTX
Inheritance in c++
PPTX
Static Data Members and Member Functions
PPTX
Constructors and destructors
PPTX
Dynamic memory allocation in c++
PPTX
Storage classes in c++
PDF
Constructor and Destructor
PPTX
I/O Streams
PPTX
Constructors in C++.pptx
PPT
PPTX
Java class,object,method introduction
PPTX
C# classes objects
PPTX
Functions in python slide share
PPT
Operator Overloading
Constructor
Functions in c++
Strings
Function in c program
Cascading Style Sheets
Memory Management C++ (Peeling operator new() and delete())
classes and objects in C++
Inheritance in c++
Static Data Members and Member Functions
Constructors and destructors
Dynamic memory allocation in c++
Storage classes in c++
Constructor and Destructor
I/O Streams
Constructors in C++.pptx
Java class,object,method introduction
C# classes objects
Functions in python slide share
Operator Overloading
Ad

Similar to Constructor and destructor in C++ (20)

PPTX
constructors shailee.pptxhhhtyygdxixixxxxix
PPT
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
PPTX
An introduction to Constructors and destructors in c++ .pptx
PPTX
constructor in object oriented program.pptx
PPTX
Constructor and destructor
PPTX
Constructor and Destructor
PPTX
Learning C++ - Class 4
PPTX
PDF
Constructors & Destructors [Compatibility Mode].pdf
PPT
Constructors and destructors in C++
PDF
Constructors and destructors
PPTX
C++ Unit-III Lecture-3a-C++ Programming Concepts
PPT
Bca 2nd sem u-2 classes & objects
PPTX
Constructors and Destructors in C++.pptx
PPT
Constructor
PPT
Mca 2nd sem u-2 classes & objects
PPTX
constructocvbcvbcvbcvbr-Destructor (1).pptx
PPT
Constructor,destructors cpp
PPTX
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
PPTX
constructors shailee.pptxhhhtyygdxixixxxxix
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
An introduction to Constructors and destructors in c++ .pptx
constructor in object oriented program.pptx
Constructor and destructor
Constructor and Destructor
Learning C++ - Class 4
Constructors & Destructors [Compatibility Mode].pdf
Constructors and destructors in C++
Constructors and destructors
C++ Unit-III Lecture-3a-C++ Programming Concepts
Bca 2nd sem u-2 classes & objects
Constructors and Destructors in C++.pptx
Constructor
Mca 2nd sem u-2 classes & objects
constructocvbcvbcvbcvbr-Destructor (1).pptx
Constructor,destructors cpp
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
Ad

More from Carelon Global Solutions (20)

PPT
Constructors and destructors in C++ part 2
PPT
Classes and objects
PPT
PPT
Virtual Function
DOC
Major project synopsis format
DOCX
Docslide.net soyabean milk-project-class-12
DOCX
Physics first page
DOCX
Uses of transformer
DOCX
Theory and working
DOCX
Main page vishnu
DOCX
Main page v physics
DOCX
Main page saurabh
DOCX
DOCX
Efficiency and energy losses
DOCX
DOCX
DOCX
Acknowledgement
DOCX
Principle construction
Constructors and destructors in C++ part 2
Classes and objects
Virtual Function
Major project synopsis format
Docslide.net soyabean milk-project-class-12
Physics first page
Uses of transformer
Theory and working
Main page vishnu
Main page v physics
Main page saurabh
Efficiency and energy losses
Acknowledgement
Principle construction

Recently uploaded (20)

PDF
PPT on Performance Review to get promotions
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PPTX
web development for engineering and engineering
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PDF
BIO-INSPIRED HORMONAL MODULATION AND ADAPTIVE ORCHESTRATION IN S-AI-GPT
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPTX
additive manufacturing of ss316l using mig welding
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
DOCX
573137875-Attendance-Management-System-original
PPT
Project quality management in manufacturing
PPTX
Fundamentals of safety and accident prevention -final (1).pptx
PDF
737-MAX_SRG.pdf student reference guides
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
Artificial Intelligence
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PPTX
Safety Seminar civil to be ensured for safe working.
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPT on Performance Review to get promotions
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
Embodied AI: Ushering in the Next Era of Intelligent Systems
Foundation to blockchain - A guide to Blockchain Tech
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
web development for engineering and engineering
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
BIO-INSPIRED HORMONAL MODULATION AND ADAPTIVE ORCHESTRATION IN S-AI-GPT
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
additive manufacturing of ss316l using mig welding
Automation-in-Manufacturing-Chapter-Introduction.pdf
573137875-Attendance-Management-System-original
Project quality management in manufacturing
Fundamentals of safety and accident prevention -final (1).pptx
737-MAX_SRG.pdf student reference guides
Model Code of Practice - Construction Work - 21102022 .pdf
Artificial Intelligence
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
Safety Seminar civil to be ensured for safe working.
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx

Constructor and destructor in C++

  • 2. Constructors A special member function having same name as that of its class which is used to initialize some valid values to the member variables.
  • 3. Key points while defining constructor A constructor has same name as that of the class to which it belongs.  A constructor is executed automatically whenever the object is created A constructor doesn`t have a return type, not even void  We can declare more than one constructor in a class. These constructor differ in there parameter list. If you don’t provide a constructor of your own then the compiler generates a default constructor (expects no parameters and has an empty body). A constructor can preferably be used for initialization and not for inputoutput operations.
  • 4. • They can’t be inherited; through a derived class, can call the base class constructor. • Like other C++ functions, they can have default arguments. • Constructors can’t be virtual. • Constructors can be inside the class definition or outside the class definition. • Constructor can’t be friend function. • They can’t be used in union.
  • 5. Contd.. • Constructor should be declared in the public section of the class. If it is not declared in public section of the class then the whole class become private . By doing this the object of the class created from outside cannot invoke the constructor which is the first member function to be executed automatically.
  • 7. Example #include<iostream.h> #include<conio.h> class Rectangle { private: int length,breadth; public: Rectangle() { length=5,breadth=6; } void area() { int a=(length*breadth); cout<<"area is"<<a; } }; void main() { clrscr(); Rectangle r1; r1.area(); getch(); }
  • 8. TYPES OF CONSTRUCTOR • 1.Default Constructor • 2.Parameterized Constructor • 3.Copy Constructor
  • 9. Parameterized Constructor In order to initialize various data elements of different objects with different values when they are created. C++ permits us to achieve this objects by passing argument to the constructor function when the object are created . The constructor that can take arguments are called parameterized constructors
  • 10. class abc { int m, n; public: abc (int x, int y); // parameterized constructor ................ ................. }; abc : : abc (int x, int y) { m = x; n = y; }
  • 11. Parameterized constructor #include<iostream.h> #include<conio.h> class Rectangle { private: int length,breadth; public: Rectangle(int a,int b) { length=a; breadth=b; } void area() { int a=(length*breadth); cout<<"area is="<<a; } }; void main() { Rectangle r1(5,6); Rectangle r2(7,8); clrscr(); r1.area();cout<<endl; r2.area(); getch(); }
  • 12. Copy constructor • A copy constructor is a constructor that creates a new object using an existing object of the same class. • and initializes each data member of newly created object with corresponding data member of existing object passed as argumnt. • since it creates a copy of an existing object so it is called copy constructor.
  • 13. Example class counter { Int c; public: Counter(int a) //single parameter constructor { c=a; } counter(counter &ob) //copy constructor { cout<<“copy constructor invoked”; c=ob.c; } }
  • 14. void show() { cout<<c; } }; void main() { clrscr(); counter C1(10); counter C2(C1);// call copy constructor C1.show(); C2.show(); getch(); }
  • 15. Another example of copy constructor #include<iostream> #include<conio.h> using namespace std; class Point { private: int x, y; public: Point(int x1, int y1) { x = x1; y = y1; }
  • 16. // Copy constructor Point(const Point &p2) { x = p2.x; y = p2.y; } int getX() { return x; } int getY() { return y; } };
  • 17. int main() { Point p1(10, 15); // Normal constructor is called here Point p2 = p1; // Copy constructor is called here // Let us access values assigned by constructors cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY(); cout << "np2.x = " << p2.getX() << ", p2.y = " << p2.getY(); return 0; }
  • 18. class code { int id; public: code() { } code(int a) { id = a; } code (code & x) { id = x. id; } void display() { cout<<id; } }; int main() { code A(100); code B(A); code C = A; code D; D = A; A.display(); B.display(); C.display(); D.display(); getch(); return 0; }
  • 19. Destructors Is a member function having same name as that of constructor but it is preceded by a tilde(~) symbol and is executed automatically when object of a class is destroyed
  • 20. Key points while defining destructor • A destructor has same name as that of the class to which it belongs preceded by tilde(~)sign. • A destructor is executed automatically whenever the object is destroyed. • A destructor doesn`t have a return type, not even void and no arguments • There is only one destructor in class . • If you don’t provide a destructor of your own then the compiler generates a default destructor • A destructor can be used to deallocate memory for an object and declared in the public section.
  • 21. Need for Destructors • To de-initialize the objects when they are destroyed • To clear memory space occupied by a data member.
  • 23. Note • Execute the program in Turbo c++. • To see the output, press Alt+F5
  • 24. Program on destructor Class sample { Public: Sample { Cout<<“object born”<<endl; }
  • 26. int main() { sample s; Cout<<“main terminated”<<endl; getch(); return 0; }
  • 27. Example #include<iostream.h> #include<conio.h> class counter { int id; public: counter(int i) { id=i; cout<<“contructor of object with id=”<<id;
  • 28. ~counter() { cout<<“destructor with id=”<<id; } }; void main() { counter c1(1); counter c2(2); counter c3(3); cout<<“n end of main”; getch(); }
  • 29. • Output constructor of object with id=1 constructor of object with id=2 constructor of object with id=3 End of main destructor with id=3 destructor with id=2 destructor with id=1 Note ::Destructor Always deallocate memory in reverse order.
  • 30. 1 Statically allocated object for class A in C++ is A *obj = new A(); A obj; A obj = new A(); None
  • 31. When you create an object of a class A like A obj ; then which one will be called automatically A Constructor B Destructor C Copy constructor D Assignment operator
  • 32. 3 Data members and member functions of a class in C++ program are by default protected public private None
  • 33. 4 Which operator is used to allocate an object dynamically of a class in C++? Scope resolution operator Conditional operator New operator Membership access
  • 34. The static member functions __________________ a) Have access to all the members of a class b) Have access to only constant members of a class c.) Have access to only the static members of a class d) Have direct access to all other class members also
  • 35. The static member functions ____________________ a.) Can be called using class name b) Can be called using program name c) Can be called directly d) Can’t be called outside the function
  • 36. Which among the following is true? a) Static member functions can be overloaded b.) Static member functions can’t be overloaded c) Static member functions can be overloaded using derived classes d) Static member functions are implicitly overloaded
  • 37. Which keyword should be used to declare the static member functions? a.) static b) stat c) const d) common
  • 38. Assume class TEST. Which of the following statements is/are responsible to invoke copy constructor? a. TEST T2(T1) b. TEST T4 = T1 c. T2 = T1 D). both a and b
  • 39. Which of the following statements are not true about destructor? 1. It is invoked when object goes out of the scope 2. Like constructor, it can also have parameters 3. It can be virtual 4. It can be declared in private section 5. It bears same name as that of the class and precedes Lambda sign. a. Only 2, 3, 5 b. Only 2, 3, 4 c). Only 2, 4, 5 d. Only 3, 4, 5
  • 40. A Constructor that does not have any parameters is called____________ Constructor. a. Custom b. Dynamic c. Static d). Default
  • 41. Which of the followings are true about constructors? 1. A class can have more than one constructor. 2. They can be inherited. 3. Their address can be referred. 4. Constructors cannot be declared in protected section of the class. 5. Constructors cannot return values. a. Only 1,2,4 b. 1,2,4,5 c. 1,3,5 d.) 1,4,5
  • 42. In a program, If there exists a function template with two parameters and normal function say void add(int , int), so add(3,4) will _____________________ . a. Invoke function template body as it is generic one b.) Invokes normal function as it exactly matches with its prototype c. Not be called and Compiler issues warning d. Not be called and Compiler issues ambiguity in calling add()