Is the following approach good?
class TA { };
class TB : TA { };
std::shared_ptr<TA> spta;
spta.reset(new TB);
There's one problem with the code shown, TB
must inherit publicly from TA
. You have a shared_ptr<TA>
, so the pointer you want to store in it must be convertible to TA
, but with private
inheritance, the base is inaccessible so your code will not compile.
class TA { };
class TB : public TA { };
Beyond this, the code has no errors and is well-behaved. Typically, when you perform polymorphic deletion of a derived class instance through a base class pointer, you need the base class' destructor to be virtual
so the derived class destructor is called, but in case of shared_ptr
this is not necessary. shared_ptr::reset
is a function template that'll accept any Y*
that is convertible to the managed pointer type. The same is true for shared_ptr
's constructor template.
That being said, you should prefer making the base class' destructor virtual
, especially if the classes involved have other virtual
functions.
No, it is not for TA
is private.
Moreover, as suggested in the comments, the destructor of the base class ought to be virtual. It is usually a good practice, for you cannot guarantee that instances of your classes will be used only with shared pointers.
To have it working, you must at least modify these lines:
class TA { };
class TB : TA { };
As it follows:
class TA { virtual ~TA() { } };
class TB : public TA { };
Those ones are good as the following example is good:
class TA { virtual ~TA() { } };
class TB : public TA { };
TA *spta = nullptr;
spta = new TB;
It mainly depends on what good means for you. It's legal, at least.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With