C++ Constructor and Destructor
Constructor is a special member function whose name is same as the name of class name. Constructor is used to initialize the objects of class. Each time the constructor method is invoked when an object is created. It constructs the values of data member of the class so it is called as constructor.
Constructor declaration and definition
1 2 3 4 5 6 7 8 9 10 11 |
class className{ //data member; public: className(returnType); //constructor declaration ...... }; className :: className(returnType){ //constructor definition //data member= initialize; } |
When an object of class is created it automatically initializes the data member inside constructor definition. For example the statement:
1 2 3 |
className objectName; |
create object of class as well as initialize the data member.
C++ Types of Constructor
Constructor is categories into different types. These are:
- Default constructor
- Parameterize constructor
- Copy constructor
- Dynamic constructor