Home »
Aptitude Questions and Answers »
C++ Aptitude Questions and Answers
C++ constructor, destructor aptitude questions and answers (set 3)
C++ constructor and destructor questions: This section contains aptitude questions and answers (MCQs) on Constructors and Destructors in C++.
Submitted by IncludeHelp, on May 03, 2019
List of C++ Constructor and Destructor Aptitude Questions & Answers
1) A constructor is called when an object is being created?
- True
- False
Correct Answer: 1
True
No matter, you have created constructors or not in the class, if there is no constructor created by you, constructors are added to the class and when we an object is being created constructor gets called.
2) If you created a parameterized and a copy constructor in the class and you create an object with no arguments (0 arguments), what will be the output?
- Program will execute successfully
- A compile-time will occur
- A run-time error will occur
- A syntax error will occur
Correct Answer - 2
A compile time will occur
If we create any constructor in the class, no other constructor will be added. Thus, a compile-time error will occur.
3) When a destructor is called?
- When an object is being created
- After destroying the object
- We need to call destructor explicitly
- Just before destroying an object
Correct Answer - 4
Just before destroying an object
When an object is being destroyed, destructor is called.
4) What will be the output of the following code?
#include <iostream>
using namespace std;
//class definition
class Example {
public:
void ~Example()
{
cout << "Destroying the object";
}
};
//main() code
int main()
{
Example Ex;
return 0;
}
- Run-time error
- Compile-time error
- Destroying the object
- Executes successfully but no output
Correct Answer - 2
Compile-time error
Consider the destructor declaration void ~Example(), note that – destructor does not have any return type. Thus, a compile-time error occurs.
The output will be,
main.cpp:7:23: error: return type specification for destructor invalid
void ~Example()
^
5) What will be the output of the following code?
#include <iostream>
using namespace std;
//class definition
class Example {
private:
int a;
int b;
public:
Example(int a, int b)
{
this->a = a;
this->b = b;
}
int get_a()
{
return a;
}
int get_b()
{
return b;
}
};
//main() code
int main()
{
Example Ex(10, 20);
cout << "a = " << Ex.get_a() << ", b = " << Ex.get_b();
return 0;
}
- Compile time error
- Run time error
- a = 10, b = 10
- a = 10, b = 20
Correct Answer - 4
a = 10, b = 20
There is no error in the program; we created a parameterized constructor and created only an object with the parameters.