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;
}
This article has been dead for over six months. Start a new discussion instead.