Destructors


1
Question 1
Can destuctors be private in C++?
A
Yes
B
No
Destructors    
Discuss it


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;
}
A
0
B
3
C
10
D
None of the above
Destructors    
Discuss it


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?
A
Yes
B
No
Destructors    
Discuss it


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;
}
A
constructor for id 1
constructor for id 2
constructor for id 3
destructor for id 3
destructor for id 2
destructor for id 1
B
constructor for id 1
constructor for id 2
constructor for id 3
destructor for id 1
destructor for id 2
destructor for id 3
C
Compiler Dependent.
D
constructor for id 1
destructor for id 1
Destructors    
Discuss it


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++?
A
Yes
B
No
Destructors    
Discuss it


Question 5 Explanation: 
See http://www.geeksforgeeks.org/g-fact-37/
There are 5 questions to complete.
1

Company Wise Coding Practice    Topic Wise Coding Practice