Lisa Ann
Lisa Ann

Reputation: 3485

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

We have:

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:

Upvotes: 1

Views: 203

Answers (1)

R Sahu
R Sahu

Reputation: 206577

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.

Upvotes: 5

Related Questions