delete by base class pointer?

G

Gernot Frisch

class Base{};
class Obj : public Base{};

std::vector<Base*> vpBase;
Obj o = new Obj();
vpBase.push_back(&o);

// Can I safely do this: ?
delete vpBase[0];

Thank you,
 
P

Peter Koch Larsen

Gernot Frisch said:
class Base{};
class Obj : public Base{};

std::vector<Base*> vpBase;
Obj o = new Obj();
vpBase.push_back(&o);

// Can I safely do this: ?
delete vpBase[0];

Thank you,
No - undefined. But for most implementations this will turn out okay. Still
it is a silly example - there's not much going on here.

/Peter
 
K

Karl Heinz Buchegger

Gernot said:
class Base{};
class Obj : public Base{};

std::vector<Base*> vpBase;
Obj o = new Obj();
vpBase.push_back(&o);

// Can I safely do this: ?
delete vpBase[0];

No. The destructor in the base class has
to be virtual.

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

Now you are safe.
 
G

Gernot Frisch

Karl Heinz Buchegger said:
Gernot said:
class Base{};
class Obj : public Base{};

std::vector<Base*> vpBase;
Obj o = new Obj();
vpBase.push_back(&o);

// Can I safely do this: ?
delete vpBase[0];

No. The destructor in the base class has
to be virtual.

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

Now you are safe.

Bingo. Now I completele understand 'virtual'. Thank you very much.
 

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

Forum statistics

Threads
474,184
Messages
2,570,973
Members
47,528
Latest member
AnaHawley8

Latest Threads

Top