Home »
Aptitude Questions and Answers »
C++ Aptitude Questions and Answers
C++ constructor, destructor aptitude questions and answers (set 2)
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) Constructor(s) which is/are added automatically with a class, if we do not create our own constructor?
- Default Constructor
- Copy Constructor
- Both default and copy constructors
- None
Correct Answer: 3
Both default and copy constructors
In C++ class implementation, if we do not create any constructor, the default and copy constructors are added automatically to the class.
2) Does assignment operator implement automatically with the class?
- Yes
- No
Correct Answer - 2
Yes
If we do not implement the assignment operator, it automatically added to the class.
3) What will be the output of the following code?
#include<iostream>
using namespace std;
//class definition
class Example {
Example() {
cout << "Constructor called";
}
};
//main() code
int main()
{
Example Ex;
return 0;
}
- Constructor called
- Program successfully executed – no output
- Compile time error
- Run time error
Correct Answer - 3
Compile time error
In the class definition, there is no access modifier is specified, thus (as per the standard) all member functions and data members are private by default. And, the constructor cannot be a private.
This will be the output
main.cpp:6:5: error: 'Example::Example()' is private
Example() {
4) What will be the output of the following code?
#include <iostream>
using namespace std;
//class definition
class Example {
public:
Example()
{
cout << "Constructor called ";
}
};
//main() code
int main()
{
Example Ex1, Ex2;
return 0;
}
- Constructor called
- Constructor called Constructor called
- Compile time error
- Run time error
Correct Answer - 2
Constructor called Constructor called
In the class definition, the constructor is public, so there is no any compile time or run time error. We are creating two objects “Ex1” and “Ex2” of “Example” class; constructor will be called two times. Thus, the output will be "Constructor called Constructor called".
5) What will be the output of the following code?
#include <iostream>
using namespace std;
//class definition
class Example {
public:
int a;
int b;
};
//main() code
int main()
{
Example Ex1 = { 10, 20 };
cout << "a = " << Ex1.a << ", b = " << Ex1.b;
return 0;
}
- Compile time error
- Run time error
- a = 10, b = 20
- a = 10, b = 10
Correct Answer - 3
a = 10, b = 20
Like structures, we can initialize class's public data members (using initializer list) like this Example Ex1 = {10, 20}; so, 10 will be assigned to a and 20 will be assigned to b. Thus, the output will be a = 10, b = 20.