Explain the need for "Virtual Destructor"?

Answers were Sorted based on User's Feedback



Explain the need for "Virtual Destructor"?..

Answer / lylez00

If A is a base class, and from that, B is derived, and a
dynamically allocated object of type B is deleted via a
pointer of type A, then B's destructor will not be invoked
unless A's destructor is virtual.

A *a = new B();
delete a; // won't invoke B's destructor unless A's
destructor is virtual

Is This Answer Correct ?    12 Yes 3 No

Explain the need for "Virtual Destructor"?..

Answer / p govind rao

A destructor can be declare virtual. virtual destructor is
mainly useful during inheritance.

class base
{
public:
base(){}
virtual ~base(){}
};

class derv
{ char *p;
public :
derv(){ptr=nes char[2];}
~derv(){delete ptr;}

} ;

main()
{
base *baseptr=new derv();
delete baseptr;
}

If base class, and derived class, and a dynamically
allocated object of type derived is deleted via a pointer
of type base, then derived's destructor will not be invoked
unless base's destructor is virtual.

base *baseptr = new derv();
delete baseptr; // won't invoke B's destructor unless A's
destructor is virtual

Is This Answer Correct ?    6 Yes 0 No

Post New Answer

More C++ General Interview Questions

What are static and dynamic type checking?

0 Answers  


Write a program for Divide a number with 2 and Print the output ( NOTE: Check for divide by zero error).

0 Answers  


Write a struct time where integer m, h, s are its members?

0 Answers  


3- Write a program to find larger and smaller of the two numbers.

4 Answers   Luminous,


How to declare a pointer to an array of integers?

0 Answers  


Why do we use structure in c++?

0 Answers  


What is meant by a delegate?

0 Answers  


Is sorted c++?

0 Answers  


write a porgram in c++ that reads an integer and print the biggest digit in the number

0 Answers  


Give 2 examples of a code optimization?

4 Answers  


Which programming language should I learn first?

0 Answers  


Can we use this pointer inside static member function?

0 Answers  


Categories