why do we need a virtuaal destructor

given the coDe

1
2
3
4
5
6
7
8
9
  class A{
public
A();
~A();
}
class B: public A
public:
B();
virtual ~B()


why do we need a virutal destructor? , i think that the object B will be ended because A is composed of B and not because of the virtual destructor , am i right? so why do we need the virtual destructor?
A virtual destructor works similarly to normal virtual functions:

1
2
3
4
5
6
7
A* ptr = new /* ? */;  // let's say it's an A or B object, we don't know which it is

ptr->someFunc();  // will call A::someFunc if someFunc is not virtual
                  // or will call B::someFunc if someFunc IS virtual

delete ptr;  // will call A's dtor if not virtual
             // will call B's dtor if IS virtual 



If we have a B object here, failure to call B's dtor could lead to memory leaks, since not everything in B will be properly destructed.
on the line delete ptr;
if it is virtual a dtor will not be called?

and secondly on my example
, i think that the object B dtor will be ended because A is composed of B and not because of the virtual destructor , am i right?
if it is virtual a dtor will not be called?


If you are calling a non-virtual function through a pointer... the function of whatever class the pointer's type is gets called. IE, if you call it with an A pointer, it will call the A function:

1
2
3
4
5
// assuming A has no virtual members
A* ptr = new B;

ptr->func();  // <-  calls A::func... NOT B::func... because we have an A pointer
delete ptr;  // <-  calls A::~A... NOT B::~B... because we have an A pointer 



If you are calling a virtual function through a pointer... the function of whatever class the object actually is gets called. IE, if you have an A pointer that points to a B object... the B function gets called:

1
2
3
4
5
// assuming A has all virtual members
A* ptr = new B;

ptr->func();  // <- calls B::func because we are pointing to a B
delete ptr; // <- calls B::~B because we are pointing to a B 



and secondly on my example


In your example, A's dtor is not virtual, so you could potentially have a problem if you delete an A pointer. B's dtor being virtual does not really help you unless you are deriving other classes from B.

, i think that the object B dtor will be ended because A is composed of B and not because of the virtual destructor , am i right?


I'm not sure I'm understanding this question.

B's dtor will call A's dtor because B derives from A. This will happen regardless of whether or not the dtors are virtual.

A's dtor will never call B's dtor.
Topic archived. No new replies allowed.