I am a little confused with new smart pointers. I want to use one pointer to point at two different objects of sibling classes (same parent).
so basically I have a parent class Parent
and two child classes Child1
and Child2
class Parent{
virtual void foo() = 0;
};
class Child1 : public Parent{
void foo(){
//something
}
}
class Child2 : public Parent{
void foo(){
//something different
}
}
The pointer say ptr
is first pointing at Child1
and then it should point at Child2
Doing so I want to use the same pointer to behave differently as per the implementations inside those sibling classes.
I think,
Parent ptr = new Child1()
a non smart pointers way, should work in this case if I do (Child2 *)ptr
But I am sure there would be a better way through smart pointers.
I know that reinterpret_ptr does have some usecase around this topic but i couldn t understand the explanation on gfg. ALSO my main Question is How do I declare this pointer?
unique_ptr<Parent> ptr = make_unique<Child1>();
?