Reputation: 3485
We have:
Base
;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:
MakeSomething()
virtual in Base
, because Base
belongs to a third-party's library which I can just inherit from;boost::shared_ptr< Base >
, I cannot go straight with a boost::shared_ptr< Derived >
;Upvotes: 1
Views: 203
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):
virtual
member functions in Base
, Derived
, ordynamic_cast
appropriately to get a pointer to Derived
.Upvotes: 5