Hey everyone! I'm writing some program and im using a vector tp hold pointers to objects..
i will create new instances of the objects and my code should automatically destroy each object present in the vector.

theres three types of classes stored in the vector : BaseClass, ChildClass1(inherited from BaseClass) and ChildClass2(inherited from BaseClass).

when the objects are destroyed, each time the destructor of BaseClass is called even if the object if of type ChilsClass1 or ChildClass2..

i.e : when deleting childclass1 (see in code below) I only get "BaseClass Destructor".

so is it possible to call the appropriate destructor of each class when deleting the objects from the vector?

thanks.

#include <vector>

class BaseClass
{
public:
	BaseClass()
	{
		printf("BaseClass Constructor\n");
	};
	~BaseClass()
	{
		printf("BaseClass Destructor\n");
	};
};

class ChildClass1 : BaseClass
{
public:
	ChildClass1()
	{
		printf("ChildClass1 Constructor\n");
	};
	~ChildClass1()
	{
		printf("ChildClass1 Destructor\n");
	};
};

class ChildClass2 : BaseClass
{
public:
	ChildClass2()
	{
		printf("ChildClass2 Constructor\n");
	};
	~ChildClass2()
	{
		printf("ChildClass2 Destructor\n");
	};
};

int main()
{
	std::vector<BaseClass*> classes;
	BaseClass * baseclass1 = new BaseClass;
	ChildClass1 * childclass1 = new ChildClass1;
	ChildClass2 * childclass2 = new ChildClass2;
	classes.push_back(baseclass1);
	classes.push_back((BaseClass*)childclass1);
	classes.push_back((BaseClass*)childclass2);
	for (unsigned int i = 0; i < classes.size(); i++)
	{
		delete classes[i];
	}
	return 0;
}

Recommended Answers

All 3 Replies

Your base class should have a virtual destructor.

You need to define the destructor of BaseClass to be virtual.

thanks alot! haha how could i not think of that :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.