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

Edit

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
  1. #include<iostream>
  2. using namespace std;
  3. class Base
  4. {
  5. public:
  6. Base()
  7. {
  8. cout"Constructing base ";
  9. }
  10. ~Base()
  11. {
  12. cout"Destructing base ";
  13. }
  14. };
  15. class Derived:public Base
  16. {
  17. public:
  18. Derived()
  19. {
  20. cout"Constructing derived ";
  21. }
  22. ~Derived()
  23. {
  24. cout"Destructing derived ";
  25. }
  26. };
  27. int main(void)
  28. {
  29. Derived d =new Derived();
  30. Base b =d;
  31. delete b;
  32. getchar();
  33. return 0;
  34. }
  • Output:

Constructing base

Constructing derived

Constructing base