Constructor in C++
Constructor in C++
A Constructor is a special member method which will be called implicitly (automatically) whenever an object of class is created. In other words, it is a member function which initializes a class which is called automatically whenever a new instance of a class is created.
Features of Constructor
- The same name as the class itself.
- no return type.
Syntax
classname() { .... }
Note: If you do not specify a constructor, the compiler generates a default constructor for you (expects no parameters and has an empty body).
Why use constructor ?
The main use of constructor is placing user defined values in place of default values.
How Constructor eliminate default values ?
Constructor are mainly used for eliminate default values by user defined values, whenever we create an object of any class then its allocate memory for all the data members and initialize there default values. To eliminate these default values by user defined values we use constructor.
Example of Constructor in C++
#include<iostream.h> #include<conio.h> class sum { int a,b,c; sum() { a=10; b=20; c=a+b; cout<<"Sum: "<<c; } }; void main() { sum s; getch(); }
Output
Sum: 30
In above example when we create an object of "Sum" class then constructor of this class call and initialize user defined value in a=10 and b=20. And here we no need to call sum() constructor.
Destructor
Destructor is a member function which deletes an object. A destructor function is called automatically when the object goes out of scope:
When destructor call
- when program ends
- when a block containing temporary variables ends
- when a delete operator is called
Features of destructor
- The same name as the class but is preceded by a tilde (~)
- no arguments and return no values
Syntax
~classname() { ...... }
Note: If you do not specify a destructor, the compiler generates a default destructor for you.
Example of Destructor in C++
#include<iostream.h> #include<conio.h> class sum { int a,b,c; sum() { a=10; b=20; c=a+b; cout<<"Sum: "<<c; } ~sum() { cout<<<<endl;"call destructor"; } delay(500); }; void main() { sum s; cout<<<<endl;"call main"; getch(); }
Output
Sum: 30 call main call destructor
Explanation: In above example when you create object of class sum auto constructor of class is call and after that control goes inside main and finally before end of program destructor is call.
Types of Constructor in C++
There are three types of constructors in C++. Default constructor. Parameterized constructor. Copy constructor.
- Default constructor
- Parameterized constructor
- Copy constructor
What is a copy constructor ?
A copy constructor is a special constructor in the C++ programming language for creating a new object as a copy of an existing object.
Example
class_name (const class_name&); { ...... }