Languages [TCS Placement]: Sample Questions 124 - 124 of 131

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 124

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
  1. #include<iostream>
  2. usingnamespacestd;
  3. classBase
  4. {
  5.     public:
  6.     Base()
  7.     {
  8.         cout"Constructing base ";
  9.     }
  10.     ~Base()
  11.     {
  12.         cout"Destructing base ";
  13.     }
  14. };
  15. classDerived:publicBase
  16. {
  17.     public:
  18.     Derived()
  19.     {
  20.         cout"Constructing derived ";
  21.     }
  22.     ~Derived()
  23.     {
  24.         cout"Destructing derived ";
  25.     }
  26. };
  27. intmain(void)
  28. {
  29.     Derived ⚹d =newDerived();
  30.     Base ⚹b =d;
  31.     deleteb;
  32.     getchar();
  33.     return0;
  34. }
  • Output:

Constructing base

Constructing derived

Constructing base

Developed by: