I have the base class and the class that inherits the base class:
class base
{
};
class derived : public base
{
std::string str;
};
I need to manage a derived class using the pointer to the base class, but the following code causes a memory leak:
base* ptr = new derived();
delete ptr;
Have I to cast ptr, or there are better alternatives?
You need a virtual destructor in the base class so the destructor of the derived class is found and called at runtime. See this question and answer for more detail.