I have a Base
class, with two derived classes DerivedA
and DerivedB
and a factory method that returns a pointer Base*
.
Base* GetClass(int choice)
{
if (choice == 0)
return new DerivedA();
else if (choice == 1)
return new DerivedB();
throw std::invalid_argument("no no no");
}
Both DerivedA
and DerivedB
implement a method, say GetDouble()
, and this method is the only thing that interests me about constructing either of these classes:
double d = GetClass(0)->GetDouble();
My question is: when I call GetClass(0) I create a pointer that should be deleted. However, I am not instantiating it to an object. Should I still need to delete it?
Something like:
Base* c = GetClass(0);
double d = c->GetDouble();
delete c;
How would that work with std::unique_ptr
?
Thank you in advance.
PS: I think there are related questions, like this and this, but mine is a little more specific.