This article is mainly focused on the most repeatedly asked and the latest updated C++ constructors and destructors interview questions that are appearing in most of the C++ interviews.
If you are looking for “C++ constructors and destructors interview questions ” or “advanced questions on constructors and destructors in C++, then you at the right place. Here I have tried to create some collection of “Some interview questions with answers related to the constructors and destructors in C+ ” that might ask by your interviewer.
I hope these C++ interview questions with the answer will be helpful. If you have any other important questions on Inheritance in C++ programming and concept, then please write in the comment box. It will be helpful for others.
Q #1) What is a constructor?
Class constructors in C++ are special member functions of a class and it initializes the object of a class. It is called by the compiler (automatically) whenever we create new objects of that class. The name of the constructor must be the same as the name of the class and it does not return anything.
One point is important that constructor has a secret argument and this argument is “this pointer” (Address of the object for which it is being called).
Q #2) Is the default constructor exists in C++?
If you will not create own constructor, then yes compiler will create a default constructor for you.
Q #3) Can a constructor throw an exception? How to handle the error when the constructor fails?
The constructor never throws an error.
Q #4) What is the purpose of using a destructor in C++?
The main purpose of the destructor is to free all the resources (opened files, opened sockets, database connections, resource locks, etc…) which are allocated during your object’s life-time.
class Myclass { private: //pointer to integer int* ptr; public: Myclass() { // default constructor ptr = new int(0); } ~Myclass() { // de-allocate the allocated memory delete ptr; } };
Q #5) What is the initializer list in C++?
The initializer list is used to initialize data members of the class. The syntax of the initializer list begins with a colon(:) and then each variable along with its value separated by a comma.
Note: The initializer list does not end in a semicolon.
Let see an example to understand the initializer list in C++, In the below code, the member variable value is initialized by the initializer list.
#include<iostream> using namespace std; class Demo { public: // initialization List Demo(int value):value(value) { cout << "Value is " << value; } private: int value; }; int main() { Demo obj(10); return 0; }
Output:
Value is 10
Q #6) When do we use the Initializer List in C++?
In the above question, we had seen, what is the initializer list in C++. Now let us see the situation where we have to use the Initializer List in C++.
1. In the initialization of reference members:
A reference member must be initialized using Initializer List.
#include<iostream> using namespace std; class Test { int &m_rData; public: Test(int & rData):m_rData(rData) {} //Initializer list must be used int getData() { return m_rData; } }; int main() { int data = 27; Test obj(data); cout<<"m_rData is " << obj.getData()<<endl; data = 06; cout<<"m_rData is " << obj.getData()<<endl; return 0; }
Output:
m_rData is 27
m_rData is 6
2. In the initialization of non-static const data members:
const data members must be initialized using Initializer List.
#include<iostream> using namespace std; class Test { const int m_data; public: Test(int x):m_data(x) {} //Initializer list must be used int getData() { return m_data; } }; int main() { int data = 27; Test obj(data); cout<<"m_data is " << obj.getData()<<endl; return 0; }
Output:
m_data is 27
3. In the initialization of member objects which do not have default constructor:
See the below example, an object “a” of class “A” is a data member of class “B”, and “A” doesn’t have a default constructor. Initializer List must be used to initialize “a”.
#include <iostream> using namespace std; class A { int i; public: A(int ); }; A::A(int arg) { i = arg; cout << "A's Constructor called: Value of i: " << i << endl; } class B { //obj of class A A a; public: B(int ); }; B::B(int x):a(x) //Initializer list must be used { cout << "B's Constructor called"; } int main() { B obj(10); return 0; }
Output:
A’s Constructor called: Value of i: 10
B’s Constructor called
4. In the initialization of base class members :
You have to initialize the base class members using the initialization list.
#include <iostream> using namespace std; class A { int i; public: A(int ); }; A::A(int arg) { i = arg; cout << "A's Constructor called: Value of i: " << i << endl; } class B: A { public: B(int ); }; B::B(int x):A(x) //Initializer list must be used { cout << "B's Constructor called"; } int main() { B obj(10); return 0; }
Output:
A’s Constructor called: Value of i: 10
B’s Constructor called
5. When constructor’s parameter name is the same as the data member:
If the constructor’s parameter name is the same as the data member name then the data member must be initialized either using this pointer or Initializer List.
#include <iostream> using namespace std; class Test { int data; public: Test(int data):data(data) { } int getData() const { return data; } }; int main() { Test obj(27); cout<<obj.getData(); return 0; }
Output:
27
6. To increase performance:
It is better to initialize all class variables in the Initializer List instead of assigning values inside the constructor body.
Q #7) What is a copy constructor?
A copy constructor is a member function that initializes an object using another object of the same class.
Syntax of copy constructor:
ClassName (const ClassName &old_obj);
Q #8) When are copy constructors called in C++?
There are some possible situation when copy constructor called in C++,
- When an object of the class is returned by value.
- When an object of the class is passed (to a function) by value as an argument.
- When an object is constructed based on another object of the same class.
- When the compiler generates a temporary object.
Q #9) Why copy constructor takes the parameter as a reference in C++?
A copy constructor is called when an object is passed by value. The copy constructor itself is a function. So if we pass an argument by value in a copy constructor, a call to copy constructor would be made to call copy constructor which becomes a non-terminating chain of calls. Therefore compiler doesn’t allow parameters to be passed by value.
Q #10) Why copy constructor argument should be const in C++?
There are some important reasons to use const in the copy constructor.
- const keyword avoids accidental changes.
- You would like to be able to create a copy of the const objects. But if you’re not passing your argument with a const qualifier, then you can’t create copies of const objects.
- You couldn’t create copies from temporary reference, because temporary objects are rvalue, and can’t be bound to reference to non-const.
Q #11) Can one constructor of a class call another constructor of the same class to initialize this object?
Onward C++11 Yes, let see an example,
#include <iostream> using namespace std; class Test { int a, b; public: Test(int x, int y) { a= x; b =y; } Test(int y) : Test( 7, y) {} void displayXY() { cout <<"a = "<<a<<endl; cout <<"b = "<<b<<endl; } }; int main() { Test obj(27); obj.displayXY(); return 0; }
Output:
a = 7
b = 27
Note: Using some tricks you can also do in C++03. If you want to know how or know the answer then please write in the comment box.
Q #12) Can a copy constructor accept an object of the same class as a parameter, in place of reference of the object? If No, why not possible?
No. It is specified in the definition of the copy constructor itself. It should generate an error if a programmer specifies a copy constructor with a first argument that is an object and not a reference.
Q #13) Are Constructors and destructors can declare as const?
Constructors and destructors can’t be declared as const or volatile. They can, however, be invoked on const or volatile objects.
Q #14) Can we make a copy constructor private?
Yes, a copy constructor can be made private. When we make a copy constructor private in a class, objects of that class become non-copyable. This is particularly useful when our class has pointers or dynamically allocated resources.
Q #15) Can you explain the order of execution in the constructor initialization list?
When a class object is created using constructors, the execution order of constructors is:
- Constructors of Virtual base classes are executed, in the order that they appear in the base list.
- Constructors of nonvirtual base classes are executed, in the declaration order.
- Constructors of class members are executed in the declaration order (regardless of their order in the initialization list).
- The body of the constructor is executed.
If you want to learn the C++11 from scratch then you can follow this course trial is free.
Your free trial is waiting.
Q #16) What is the difference between constructor and destructor?
There are the following differences between the constructor and destructor in C++.
Constructor | Destructor |
Constructor helps to initialize the object of a class. | Whereas destructor is used to destroy the instances. |
The constructor’s name is the same as the class name. | The destructor name is the same as the class name but preceded by a tiled (~) operator. |
A constructor can either accept the arguments or not. | While it can’t have any argument. |
A constructor is called when the instance or object of the class is created. | It is called while the object of the class is freed or deleted. |
A constructor is used to allocate the memory to an instance or object. | While it is used to deallocate the memory of an object of a class. |
A constructor can be overloaded. | While it can’t be overloaded. |
There is a concept of copy constructor which is used to initialize an object from another object. | While here, there is no copy destructor concept. |
Q #17) What is the conversion constructor?
A constructor with a single argument makes that constructor as conversion constructor and it can be used for type conversion. Let see an example code,
#include<iostream> using namespace std; class Demo { private: int data; public: Demo(int i) { data = i; } void Display() { cout<<" data = "<<data<<endl; } }; int main() { Demo obj(6); obj.Display(); obj = 27; // conversion constructor is called here. obj.Display(); return 0; }
Output:
data = 6
data = 27
Q #18) What is the difference between a copy constructor and an overloaded assignment operator?
A copy constructor constructs a new object by using the content of the argument object. An overloaded assignment operator assigns the contents of an existing object to another existing object of the same class.
Let see an example code,
#include<iostream> using namespace std; class Demo { public: Demo() {} Demo(const Demo &obj) { cout<<"Copy constructor called "<<endl; } Demo& operator = (const Demo &obj) { cout<<"Assignment operator called "<<endl; return *this; } }; int main() { Demo a, b; b = a; Demo c = a; return 0; }
Output:
Assignment operator called.
Copy constructor called.
Note:
b = a; // calls assignment operator, same as "b.operator=(a);" Test c = a; // calls copy constructor, same as "Test c(a);"
Q #19) What is the conversion operator in C++?
A class can have a public method for specific data type conversions. Let see an example,
#include <iostream> using namespace std; class Demo { double value; public: Demo(double data ) { value = data; } operator double() { return value; } }; int main() { Demo BooObject(3.4); /*assigning object to variable mydata of type double. Now conversion operator gets called to assign the value.*/ double mydata = BooObject; cout << mydata <<endl; }
Output:
3.4
Q #20) What is destructor in C++?
A destructor is a member function that destructs or deletes an object.
Q #21) When is the destructor called?
A destructor function is called automatically when the object goes out of scope:
- At the function ends.
- When the program ends.
- A block containing local variables ends.
- When the delete operator is called.
Q #22) Is it possible to overload the destructor of the class?
No, we can not overload the destructor of the class.
Q #23) Can I call the destructor explicitly?
No.
Q #24) How destructors are different from a normal member function.
The name of the destructors must be the same as the class name preceded by a tilde (~). Also, destructors don’t take any argument and don’t return anything.
Q #25) When do we need to write a user-defined destructor?
If we do not write our own destructor in class, the compiler creates a default destructor for us. The default destructor works fine unless we have dynamically allocated memory or pointer in class. When a class contains a pointer to memory allocated in class, we should write a destructor to release memory before the class instance is destroyed. This must be done to avoid the memory leak.
Q #26) Why a class has only one destructor?
A destructor doesn’t have parameters, so there can be only one.
Q #27) Can we have a virtual destructor in C++?
Yes, the destructor could be virtual in C++.
Q #28) When to use virtual destructors?
When we will delete an object of the derived class using a pointer to the base class that has non-virtual destructor a result in undefined behavior.
So virtual destructors are useful when you might potentially delete an instance of a derived class through a pointer to base class. Let see an example code,
#include<iostream> using namespace std; class base { public: base() { cout<<"Constructing base \n"; } virtual ~base() { cout<<"Destructing base \n"; } }; class derived: public base { public: derived() { cout<<"Constructing derived \n"; } ~derived() { cout<<"Destructing derived \n"; } }; int main(void) { derived *d = new derived(); base *b = d; delete b; return 0; }
Output:
Constructing base Constructing derived Destructing derived Destructing base
Q #29) Can we have a virtual constructor in C++?
The Constructor can’t be virtual as the constructor is a code that is responsible for creating an instance of a class and it can’t be delegated to any other object by virtual keyword means.
Q #30) What is the default constructor?
A constructor without any arguments or with the default value for every argument is said to be a default constructor.
Q #31) What does the explicit keyword mean?
Prefixing the explicit keyword to the constructor prevents the compiler from using that constructor for implicit conversions.
Q #32) How many types of constructors exist in C++?
Mainly in c++ there are three types of constructors exist “Default constructor”, “Parameterized constructors” and “Copy constructor”. We create the constructor as per our requirement but if we will not create the constructor then the compiler automatically creates the constructor to initialize the class object.
Q #33) What is the output of the below program?
#include <iostream> using namespace std; class Myclass { public: float area; Myclass() { area = 0.00; } Myclass(int a, int b) { area = a * b; } void disp() { cout<< area<< endl; } }; int main() { Myclass obj1; Myclass obj2( 10, 20); obj1.disp(); obj2.disp(); return 0; }
Output:
0
200
Explanation: C++ allows more than one constructor.
Q #34) What is the output of the below program?
#include <iostream> using namespace std; class constructor { int x; public: constructor(short ss) { cout<< "Short" << endl; } constructor(int xx) { cout<< "Int" << endl; } constructor(float ff) { cout<< "Float" << endl; } }; int main() { constructor c('A'); return 0; }
Output:
Int
Explanation: As ‘A’ gives the integer value i.e, 65. so, the integer constructor will be executed.
Q #35) What is the output of the below program?
#include <iostream> using namespace std; class Demo { ~Demo() { cout << "Destructor"; } public: Demo() { cout << "Constructor"; } }; int main() { Demo myDemo; }
Output:
Compiler Error.
Explanation: Destructor is private, so we can’t create the object.
Q #36) Is it possible to call one constructor from another constructor within the same class?
OfCourse, in C++, you can call one constructor from another constructor within the same class. This feature, called Constructor Delegation, was introduced in C++ 11. Delegation allows you to reuse initialization code present in one constructor within another constructor of the same class. You should remember, delegating constructors only works in the constructor’s initialization list.
Consider the below example,
class Test { public: int a, b; Test(): Test(0, 0) {} Test(int x, int y) : a(x), b(y) { cout << a << " " << b; } };
Recommended Articles for you:
- Introduction of constructor in C++.
- Interview questions on the virtual keyword in C++.
- Interview Questions on Inheritance in C++.
- C++ Interview Questions with Answers.
- How to create dynamic array in C?
- Memory Layout in C.
- 100 embedded C interview Questions.
- Python Interview Questions with Answer.
- 100 c interview questions, your interviewer might ask.
- C Interview Questions for the experience.
- File handling in C.
- C-Sharp Interview Questions.