Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of Derived class with the std::shared_ptr of Base class

Is the following approach good?

class TA      {  };
class TB : TA {  };

std::shared_ptr<TA> spta;
spta.reset(new TB);
like image 340
jnbrq -Canberk Sönmez Avatar asked Nov 22 '15 20:11

jnbrq -Canberk Sönmez


2 Answers

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.

like image 64
Praetorian Avatar answered Nov 03 '22 00:11

Praetorian


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.

like image 28
skypjack Avatar answered Nov 03 '22 01:11

skypjack