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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.