Smart pointers and virtual methods

If you want to use dynamically created objects, you will want to use smart pointers to manage their lifetime. The good news is that virtual method dispatching works through smart pointers (they are simply wrappers around object pointers), and the bad news is that the class relationships are lost when you use smart pointers. Let's examine why.

For example, the following two classes are related by inheritance:

    struct base      {          Virtual ~base() {}         virtual void who() = 0;      };      struct derived : base      {          virtual void who() { cout << "derivedn"; }      };

This is straightforward: that implement a virtual method, which indicates the type of the object. There is, a virtual destructor because we are going to hand over ...

Get Beginning C++ Programming now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.