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 the c++ access specifiers?

1 Answers  


What are the benefits of pointers?

0 Answers  


Is c++ free?

0 Answers  


Can you overload the operator+ for short integers?

0 Answers  


What is the use of namespace std in C++?

0 Answers   Hexaware,






What are the differences between java and c++?

0 Answers  


When does the c++ compiler create temporary variables?

0 Answers  


What is setf in c++?

0 Answers  


Why can you not make a constructor as const?

3 Answers  


How do you import payscale data from non SAP to SAP?is it through LSMW or any other way is there?

0 Answers  


Name four predefined macros.

0 Answers  


What is c++ best used for?

0 Answers  


Categories