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?
No, you cannot access
derived_intbecausederived_intis part ofDerived, whilebasepointeris a pointer toBase.You can do it the other way round though:
Derived classes inherit the members of the base class, not the other way around.
However, if your
basepointerwas pointing to an instance ofDerivedthen you could access it through a cast:Note that you’ll need to change your inheritance to
publicfirst: