C++ interview questions on Constructors
A constructor is a function of a class that has the same name as the class. The constructor is called at the time of the initialization of object. There are three types of constructors −
class cl_name{ cl_name(){ //This is constructor.. } }
A destructor is a method of a class that has the same name as the class preceded by a tild ~ symbol. It is called at the end of code or when the object is destroyed or goes out of scope.
class cl_name{ ~ cl_name(){} //destructor }
A constructor is a method that has the same name as a class. And the use of a constructor is to initialize the object when it is created using a new keyword.
When an object is created, the variables are initialized chunks of memory and base values if there are any.
A destructor is a method that has the same name as a class preceding a ~ symbol. The use of a destructor is to deallocate the memory chunks one the code goes out of the scope of the object or deleted using the delete keyword.
When the object is deleted the destructor is called and it deallocated all the memory blocks that were created when an object was created.
A constructor is invoked when the object of a class is created. The order in which a constructor is invoked is the same as the hierarchy of the inheritance. This means that first the object of a base class is invoked then the objects of the child class are invoked and so on.
A destructor is invoked in the reverse order as the constructor and is invoked when the object of the class is deleted. The order in which a destructor is invoked is just the opposite of the hierarchy of the inheritance. This means that first the object of child class is destroyed then the objects of the parent class are destroyed and so on.
Constructors are created by default by the compiler if a programmer doesn’t define any constructor explicitly. If the programmer defines a constructor then compiler holds its work and does not define any of it.