I want all children of a superclass to perform a similar action. So I figured I could have a method in the superclass to do so. The action requires sending a copy of (or shared_ptr to) itself as an argument to a method. But I do not know if such thing is possible or not, and if yes, how should it be done.
To clarify my question, please consider the following example. I want the printouts to be "Child" and "Parent". The current code prints out "Parent" and "Parent". Of course this is expected from this code as I am returning copying *this as a Parent type inside make_shared.
The question is if I could get the expected behavior. Please note that in the real case, there are many children, so implementing the function getPtr() in each is not that easy.
Thanks for your help.
class Parent
{
public:
std::shared_ptr<Parent> getPtr() { return std::make_shared<Parent>(*this); } // I tried make_shared<decltype(*this)> also, but the code does not compile.
virtual void printName() const { std::cout << "Parent\n"; }
};
class Child1 : public Parent {
void printName() const override { std::cout << "Child\n"; }
};
int main() {
Child1 c;
auto cPtr = c.getPtr();
cPtr->printName(); // I want this to print "Child", but it prints "Parent" (as expected)
Parent p;
auto pPtr = p.getPtr();
pPtr->printName();
}
It is not entirely clear what you are doing, but you certainly want to derive your Parent
from std::enable_shared_from_this
.
This will give you a member function shared_from_this()
(which is more or less what you want to achieve via getPtr()
).
However, it must be stressed that your Parent
objects must themselves be managed by std::shared_ptr
. I.e., this will work only and only if
std::shared_ptr<Parent> p = std::make_shared<Parent>();
Then you can use p->shared_from_this()
to give you a shared pointer.