Inheritance machanism

D

david

Here is the code:

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

class D : public B {
public:
D() { t = new int; }
~D() { delete t; }
private:
int* t;
};

void do_something()
{
B* pb = static_cast<D*> (new D());
// do something ...
delete pb;
}

My question is whether the D class' destructor is called? What happen
when I use the static_cast? Thanks in advance.
 
V

Victor Bazarov

david said:
Here is the code:

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

class D : public B {
public:
D() { t = new int; }
~D() { delete t; }

This class does not conform to the recommendations of "The Rule of
Three" (look it up).
private:
int* t;
};

void do_something()
{
B* pb = static_cast<D*> (new D());

This static cast is a NOP. Did you mean to static_cast to B*?
// do something ...
delete pb;
}

My question is whether the D class' destructor is called? What happen
when I use the static_cast? Thanks in advance.

Assuming you meant static_cast<B*>. Nothing happens. The pointer is
converted to a B*. Since you declared 'B' a public base of 'D', such
conversion is actually implicit. Using an explicit static_cast when an
implicit cast is allowed does not change anything.

Since the d-tor of 'B' is virtual, when you 'delete pb', the d-tor of D
will be called.

Why do you ask?

V
 
G

Gert-Jan de Vos

Here is the code:

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

};

class D : public B {
public:
   D() { t = new int; }
   ~D() { delete t; }
private:
   int* t;

};

void do_something()
{
    B* pb = static_cast<D*> (new D());
   // do something ...
   delete pb;

}

My question is whether the D class' destructor is called?

B's destructor is public and virtual. Therefore delete pb calls the
destructor
of the dynamic type of *pb, which is D::~D(). This in turn will call
B::B~() to
destruct the base class B subobject after the body of D::~D() has
completed.
 What happens when I use the static_cast?

Nothing since the static type of (new D) is D* already. Even
static_cast<B*>(new D())
will do the same since you assign the result to a B* and B's
destructor is virtual.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,156
Messages
2,570,878
Members
47,413
Latest member
KeiraLight

Latest Threads

Top