deleting the object problem

Hi ,
Why am i getting the error while deleting the object in the main .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47


#include <iostream>
using namespace std ; 
class Base1
{
public:
	Base1() { cout<<"\n Construction of the Base 1";	}
	virtual void Todo()  { cout<<"\n you are in to do in the base class "; } 
	~Base1() { cout<<"\n To do in the destructor of the Base1 " ; } 
};
class Derived1  : virtual public Base1
{
public:
	Derived1() { cout << "\n Derived1  constructor" ;  } 
	void Todo() {  cout<<"\n Todo function of the Derived1 class "; } 
	~Derived1() { cout<<"Distructor if Derived 1"; } 
};

class Derived2 : virtual public Base1
{
public:
	Derived2() { cout<<"\n Derived 2 Constructor "; }
	void Todo() { cout<<" \n Todo functionin the Derived 2 "; } 
	~Derived2() { cout<<"\n Destructor of the derived class . "; } 

};
class Fox : public Derived1 , public Derived2 
{
public:
	Fox() { cout<<"\n Fox constructor "; } 
	void Todo() { cout << "\n Fox to do " ; }  
	~Fox() { cout<<"\n Destructor Fox "; } 

};


int _tmain(int argc, _TCHAR* argv[])
{
	Base1* pBase = new Fox() ; 
	pBase->Todo(); 
	if( pBase )  
	delete pBase;  /// Here i get the error of assertion failed 

	return 0;
}

Please guide .
Thanks in advance
xxx

You probably want to make the destructor of Base1 virtual:
1
2
3
4
5
6
7
class Base1
{
public:
	Base1() { cout<<"\n Construction of the Base 1";	}
	virtual void Todo()  { cout<<"\n you are in to do in the base class "; } 
	virtual ~Base1() { cout<<"\n To do in the destructor of the Base1 " ; } 
};

Otherwise the object pointed to by pBase will be destructed using the Base1 destructor since it can't be overridden, which in C++ is undefined behavior (Attempting to destroy a class pointed to by a base pointer using the base destructor)

EDIT: Messed up the code tag.
Last edited on
Thanks Blacksheep it worked.
Topic archived. No new replies allowed.