views:

478

answers:

2
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?
+4  A: 

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
Peter Alexander
shouldn't he use dynamic_cast instead of static_cast?
SB
That depends whether or not he knows that it is a `Derived` or not. If you are 100% sure (as we are here) then `static_cast` is fine.
Peter Alexander
+4  A: 

You're dancing on the minefield here. The base class can never know that it's actually an instance of the derived. The safest way to do that would be to introduce a virtual function in the base:

class Base 
{ 
protected:
 virtual int &GetInt()
 {
  //Die horribly
 }

public: 
 int base_int; 
}; 

class Derived : Base 
{ 
  int &GetInt()
  {
    return derived_int;
  }
public: 
int derived_int 
}; 

basepointer->GetInt() = 0;

If basepointer points as something other that a Derived, your program will die horribly, which is the intended result.

Alternatively, you can use dynamic_cast(basepointer). But you need at least one virtual function in the Base for that, and be prepared to encounter a zero.

The static_cast<>, like some suggest, is a sure way to shoot yourself in the foot. Don't contribute to the vast cache of "unsafety of the C language family" horror stories.

Seva Alekseyev
"Alternatively, you can use dynamic_cast(basepointer). But you need at least one virtual function in the Base for that, and be prepared to encounter a zero." --> Good Point Seva.Liked It :)
mahesh