Explain the need for "Virtual Destructor"?

Answer Posted / 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       View All Answers


Please Help Members By Posting Answers For Below Questions

Difference between Abstraction and encapsulation in C++?

580


What is c++ prototype?

591


Write is a binary search tree? Write an algo and tell complexity?

599


How can we access protected and private members of a class?

591


Can a Structure contain a Pointer to itself?

612






What is a storage class? Mention the storage classes in c++.

595


Does c++ have foreach?

530


List the issue that the auto_ptr object handles?

613


What is c++ vb?

616


How do you master coding?

570


What is a flag in c++?

609


Explain the use of this pointer?

640


Does std endl flush?

613


Explain the concept of dynamic allocation of memory?

619


What is scope operator in c++?

569