C++ Interview questions based on constructors/ Destructors

C++Server Side ProgrammingProgramming

C++ interview questions on Constructors

What is a constructor?

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 −

  • Default constructor
  • Parameterized constructor
  • Copy constructor

Syntax

class cl_name{
   cl_name(){
      //This is constructor..
   }
}

What is a destructor?

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.

Syntax

class cl_name{
   ~ cl_name(){} //destructor
}

What is the use of constructor?

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.

What is the use of destructor?

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.

What is the order of constructor execution in C++?

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.

What is the order of destructor execution in C++?

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.

Is the default constructor created even if we create any other constructor?

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.

raja
Published on 19-Sep-2019 10:31:44
Advertisements