Given an object initialized like so:
Base* a = new Derived();
Container<Base> c(a);
where
class Base {
...
protected:
~Base();
}
class Derived : public Base {...};
template <typename T>
class Container {
private:
T* object;
public:
Container(T* o) : object(o) {}
void deleteObject() {
delete object; // Object must be casted to (unknown) derived type to call destructor.
}
};
Obviously this is very simplified from the actual code, but the question is how do I cast object from its templated type to its actual, derived type (if they are different), which is not known?
I cannot modify Base or Derived, or even any of the code calling Container, only the Container class itself.
If you’re able to change the creation code, you might get away with this:
And in the calling code: