deleting multible inherited objects using a base class pointer

S

Softari

Why does program crash if object is deleted using base class pointer
that is not the first base class?

Please look exaple below.


#include <iostream>
class A
{
public:
virtual void printA(){std::cout << "A"<<std::endl;}
};

class B
{
public:
virtual void printB(){std::cout << "B"<<std::endl;}
};

class AB:public A, public B
{
};

void foo(A *p){delete p;}
void bar(B *p){delete p;}
int main()
{
AB *p = new AB();
foo(p);
AB *p2 = new AB();
bar(p2); // Crash
return 0;
}

Is there a way around this. I find it quite limiting that the order of
inheritance matters to ability to call foo but not bar
Best Regards,
Jussi
 
J

John Harrison

Why does program crash if object is deleted using base class pointer
that is not the first base class?

Please look exaple below.


#include <iostream>
class A
{
public:
virtual void printA(){std::cout << "A"<<std::endl;}
};

class B
{
public:
virtual void printB(){std::cout << "B"<<std::endl;}
};

class AB:public A, public B
{
};

void foo(A *p){delete p;}
void bar(B *p){delete p;}
int main()
{
AB *p = new AB();
foo(p);
AB *p2 = new AB();
bar(p2); // Crash
return 0;
}

Is there a way around this. I find it quite limiting that the order of
inheritance matters to ability to call foo but not bar
Best Regards,
Jussi

Because you don't have a virtual destructor. It is illegal to delete any
derived object though a base class pointer unless you have a virtual
destructor. First base class, second base class makes no difference, it's
illegal always.


class A
{
public:
virtual ~A() {}
virtual void printA(){std::cout << "A"<<std::endl;}
};

class B
{
public:
virtual ~B() {}
virtual void printB(){std::cout << "B"<<std::endl;}
};

Now it should work.

john
 

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
473,995
Messages
2,570,236
Members
46,821
Latest member
AleidaSchi

Latest Threads

Top