Languages-C & C Plus Plus [TCS Placement]: Sample Questions 112 - 112 of 119
Get unlimited access to the best preparation resource for competitive exams : get questions, notes, tests, video lectures and more- for all subjects of your exam.
Question 112
Question MCQ▾
Can a class have virtual destructor?
Choices
Choice (4) | |
---|---|
a. | Yes |
b. | No |
c. | All of the above |
d. | Question does not provide sufficient data or is vague |
Answer
a.Explanation
- Any class that is inherited publicly, polymorphic or not, should have a virtual destructor.
- To put another way, if a class can be pointed to by a base class pointer, its base class should have a virtual destructor.
- If virtual, first the derived class destructor gets called, then the base class constructor
- Deleting a derived class object using a pointer to a base class that has a non-virtual destructor results in undefined behavior.
- To correct this situation, the base class should be defined with a virtual destructor
- For example
#include<iostream>
using namespace std;
class Base
{
public:
Base()
{
cout≪"Constructing base ";
}
~Base()
{
cout≪"Destructing base ";
}
};
class Derived:public Base
{
public:
Derived()
{
cout≪"Constructing derived ";
}
~Derived()
{
cout≪"Destructing derived ";
}
};
int main(void)
{
Derived ⚹d =new Derived();
Base ⚹b =d;
delete b;
getchar();
return 0;
}
- Output:
Constructing base
Constructing derived
Constructing base