0

I have a template class like this (with dynamic data):

template <class T>
class TemplateClass : public BaseClass {
public:
...
protected:
vector<T> data;
...
}

It's derived from a BaseClass because in another container class I must have all this template classes within the same vector:

class Container{
public:
...
protected:
vector<BaseClass*> elements;
}

This way I can have different types in the same vector and call TemplateClass methods just doing dynamic_cast (ej dynamic_cast<TemplateClass<int>*>(elements[i])->method(a)("a" would be an integer)). It works(the program runs) but it doesn't convince me because when I destroy the container I have to call explicitly the destructor of TemplateClass since BaseClass does not destroy data (vector): delete dynamic_cast<TemplateClass<int>*>(elements[i]) I would like to use unique_pointer but I think it would not work because it doesn't delete data (since BaseClass destructor will be called instead of TemplateClass destructor and BaseClass cannot have this template vector). Is there any alternative? I must have this TemplateClass vector. Thank You

pipespups
  • 37
  • 5
  • Related, consider using `std::vector>` instead, and managing the elements within via `std::make_shared`. You can then forego manual container enumeration at parent-destruction entirely (it will be properly handled for you, assuming you take the answer(s) below and provide a virtual dtor in the base). – WhozCraig May 27 '20 at 21:52

1 Answers1

0

You need make the destructor of BaseClass a virtual destructor.

class BaseClass
{
   virtual ~BaseClass() {}
};

With that change, the destructor of TemplateClass will be called when you delete the objects in Container::elements. In the destructor of TemplateClass, you can delete the dynamically allocated memory.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • But for example it would not solve the problem with Copy Constructor since it cannot be declared virtual. – pipespups May 27 '20 at 21:29
  • @pipespups, to suppor that, you'll have to implement a function to clone an object. See https://stackoverflow.com/questions/24939570/how-to-clone-as-derived-object-in-c. – R Sahu May 27 '20 at 21:31
  • 2
    @pipespups • you'll need a virtual `clone` function, since a copy constructor cannot be declared virtual. You'll need to make the copy constructor protected. – Eljay May 27 '20 at 21:32
  • 1
    @Eljay Constructor can stay public as it has different meaning than `clone`. It states that you want to create a new object of specific class based on the given object. Clone says you want to have new object not of hardcoded class but of the same class like the given object. It may have sense to make constructors protected but this depends on the context. – Piotr Siupa May 27 '20 at 21:54
  • @NO_NAME • agreed, in the use case given in the OP's post, if not made protected I see slicing bugs in the near future. – Eljay May 27 '20 at 22:01