C++ Access derived class member from base class pointer

Peter picture Peter · Mar 12, 2010 · Viewed 79.9k times · Source

If I allocate an object of a class Derived (with a base class of Base), and store a pointer to that object in a variable that points to the base class, how can I access the members of the Derived class?

Here's an example:

class Base
{
    public:
    int base_int;
};

class Derived : public Base
{
    public:
    int derived_int;
};

Base* basepointer = new Derived();
basepointer-> //Access derived_int here, is it possible? If so, then how?

Answer

Peter Alexander picture Peter Alexander · Mar 12, 2010

No, you cannot access derived_int because derived_int is part of Derived, while basepointer is a pointer to Base.

You can do it the other way round though:

Derived* derivedpointer = new Derived;
derivedpointer->base_int; // You can access this just fine

Derived classes inherit the members of the base class, not the other way around.

However, if your basepointer was pointing to an instance of Derived then you could access it through a cast:

Base* basepointer = new Derived;
static_cast<Derived*>(basepointer)->derived_int; // Can now access, because we have a derived pointer

Note that you'll need to change your inheritance to public first:

class Derived : public Base