I have a class, let's call it A
. There are two subclasses of class A
which are a
and b
.
I'm making a pointer of class A
like this:
A *pointer;
At some point in the program I initialize the pointer like this:
pointer = new a();
At some other point, I run a function of class A
:
pointer->function(&pointer);
This function is inside class A
(so all subclasses have it). There is a chance that when this function is called, I want to change pointer to another subclass, here is what I tried:
void A::function(A **pointer)
{
if (something)
{
delete *pointer;
*pointer = new b();
}
}
Although this works, I'm really curious if this is good practice, I'm calling delete
from inside the object and freeing the object itself, could this be undefined behavior and I got lucky it worked? Am I not understanding this right? Am I making this more complicated than it should be?