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

Consider the following code fragment: int main(void) { int m = 4; mystery ( m ); mystery ( m ); printf("%d", m); return 0; } What is the output on the monitor if mystery is defined as follows ? void mystery (int m) { m = m+3; }

2 Answers   CDAC, Wipro,


Can non-public members of another instance of the class be retrieved by the method of the same class?

0 Answers  


What do you mean by enumerated data type?

0 Answers  


What is size of empty class object

5 Answers   CA,


Explain the use of this pointer?

0 Answers  






What is type of 'this' pointer? Explain when it is get created?

0 Answers  


What is the average salary of a c++ programmer?

0 Answers  


Should I learn c or c++ or c#?

0 Answers  


What are virtual constructors/destructors?

0 Answers  


What is the difference between static link library and dynamic link library?

7 Answers   Tech Mahindra,


Define a pointer to a data member of the type pointer to pointer?

0 Answers  


Explain the static member function.

0 Answers  


Categories