Search code examples
c++pointersinheritanceshared-ptr

Derived class' method not found via dereferencing boost::shared_ptr


We have:

  • base class Base;
  • derived class Derived.

Declaration:

class Derived : public Base
{
public:
  Derived();  // ctor
  ~Derived(); // dtor
  void MakeSomething();
private:
  // some private stuff
}

Now we go to our main. This works fine:

// ...
Derived derived;
derived.MakeSomething();
// ...

On the contrary, this doesn't work:

// ...
boost::shared_ptr< Base > derived(new Derived);
derived->MakeSomething();
// ...

Compiler says:

Error: class "Base" has no member "MakeSomething"

I know it hasn't, in fact I want to call Derived's method! What am I missing with inheritance and pointers?

Additional issues:

  • I cannot declare MakeSomething() virtual in Base, because Base belongs to a third-party's library which I can just inherit from;
  • I have other classes and methods which require me to pass boost::shared_ptr< Base >, I cannot go straight with a boost::shared_ptr< Derived >;
  • ...static casting should be avoided?

Solution

  • When you use:

    boost::shared_ptr< Base > derived = ...;
    

    you can only access functions that are declared in Base through derived. The simplest analogy is to use raw pointers.

    Base* ptr = new Derived;
    

    Even though ptr points to a Derived, you cannot access member functions of Derived through the pointer.

    Your choices are (that I can think of):

    1. Define virtual member functions in Base,
    2. Create a pointer to Derived, or
    3. Use dynamic_cast appropriately to get a pointer to Derived.