C++ Destructors

Question 1
Can destructors be private in C++?
Tick
Yes
Cross
No


Question 1-Explanation: 

Destructors can be private. See Private Destructor for examples and uses of private destructors in C++.

Question 2
Predict the output of following C++ progran
#include <iostream>
using namespace std;
 
int i;
 
class A
{
public:
    ~A()
    {
        i=10;
    }
};
 
int foo()
{
    i=3;
    A ob;
    return i;
}
 
int main()
{
    cout << foo() << endl;
    return 0;
}
Cross
0
Tick
3
Cross
10
Cross
None of the above


Question 2-Explanation: 
While returning from a function, destructor is the last method to be executed. The destructor for the object “ob” is called after the value of i is copied to the return value of the function. So, before destructor could change the value of i to 10, the current value of i gets copied & hence the output is i = 3. See this for more details.
Question 3
Like constructors, can there be more than one destructors in a class?
Cross
Yes
Tick
No


Question 3-Explanation: 
There can be only one destructor in a class. Destructor\'s signature is always ~ClassNam() and they can not be passed arguments.
Question 4
#include <iostream>
using namespace std; 
class A
{
    int id;
    static int count;
public:
    A() {
        count++;
        id = count;
        cout << "constructor for id " << id << endl;
    }
    ~A() {
        cout << "destructor for id " << id << endl;
    }
};
 
int A::count = 0;
 
int main() {
    A a[3];
    return 0;
}
Tick
constructor for id 1
constructor for id 2
constructor for id 3
destructor for id 3
destructor for id 2
destructor for id 1
Cross
constructor for id 1
constructor for id 2
constructor for id 3
destructor for id 1
destructor for id 2
destructor for id 3
Cross
Compiler Dependent.
Cross
constructor for id 1
destructor for id 1


Question 4-Explanation: 
In the above program, id is a static variable and it is incremented with every object creation. Object a[0] is created first, but the object a[2] is destroyed first. Objects are always destroyed in reverse order of their creation. The reason for reverse order is, an object created later may use the previously created object. For example, consider the following code snippet.
A a;
B b(a);
In the above code, the object ‘b’ (which is created after ‘a’), may use some members of ‘a’ internally. So destruction of ‘a’ before ‘b’ may create problems. Therefore, object ‘b’ must be destroyed before ‘a’.
Question 5
Can destructors be virtual in C++?
Tick
Yes
Cross
No


Question 5-Explanation: 
There are 5 questions to complete.

  • Last Updated : 28 Sep, 2023

Share your thoughts in the comments
Similar Reads