Q18.Marks: +2.0UGC NET Paper 2: Computer Sc 23rd August 2024 Shift 1
What is the output of code given below:
#include < iostream.h >
using namespace std;
class Base {
public:
Base() {
cout << "Base Const";
}
virtual ~Base() {
cout << "Base dest";
}
};
class Derived : public Base {
public:
Derived() {
cout << "Derived Const";
}
~Derived() {
cout << "Derived dest";
}
};
int main() {
Base *b = new Derived();
delete b;
return 0;
}
1.Base Const Derived Const Derived dest Base dest✓ Correct
2.Base Const Derived Const Base dest Derived dest
3.Derived Const Base Const Base dest Derived dest
4.Base Const Derived Const Base dest
Solution
The correct answer is Base Const Derived Const Derived dest Base dest
Concept:
Virtual Destructor:
In C++, if a base class has a virtual destructor, the derived class destructors are also called when an object is deleted through a base class pointer. This ensures that the derived class resources are properly released. If the destructor is not virtual, only the base class destructor will be called, leading to resource leaks.
Explanation:
Let's analyze the provided code step by step to determine the output:
#include <iostream.h>
using namespace std;
class Base {
public:
Base() {
cout << "Base Const";
}
virtual ~Base() {
cout << "Base dest";
}
};
class Derived : public Base { // Note: The class declaration should be corrected here.
public:
Derived() {
cout << "Derived Const";
}
~Derived() {
cout << "Derived dest";
}
};
int main() {
Base *b = new Derived(); // Corrected from 'Base 'b=new Derived();' to 'Base *b = new Derived();'
delete b; // This calls the destructor
return 0;
}
Breakdown of the code:
1. Object Creation:
When `new Derived()` is called:
The constructor of `Base` is executed first because `Derived` inherits from `Base`. So, it outputs: Base Const
Then, the constructor of `Derived` is executed, which outputs: Derived Const
2. Deletion:
When `delete b;` is called, it triggers the destructor process:
The destructor of `Derived` is called first due to the virtual destructor in the Base class, which outputs: Derived dest
After that, the destructor of `Base` is called, which outputs: Base dest
Final Output Sequence: Combining the outputs:
Base Const
Derived Const
Derived dest
Base dest
Thus, the complete output of the code will be: Base ConstDerived ConstDerived destBase dest
Therefore, the correct answer is: 1) Base Const Derived Const Derived dest Base dest
(However, note that in the output there would be no spaces unless added explicitly in the `cout` statements.)