howtechstuffworks
howtechstuffworks

Reputation: 1916

I need to access a derived class member through the base class static variable

I need to access the derived class member variable through Base class variable.

Class A{

};

Class B:public A {
  int data;  
};

now I need to do something like this

A *pb = new B()
pb->data = 10;

but the problem is I cannot access the Derived member class wihtout it.

and Yeah I know how to make it work with virtual functions.

Thanks, I really appreciate your help.

Upvotes: 1

Views: 704

Answers (3)

Nathan Monteleone
Nathan Monteleone

Reputation: 5470

Without virtual functions the only thing you could do is downcast it. There's a few ways to go about that:

  • You can use dynamic_cast if you have RTTI enabled AND you have at least one virtual function in the parent class, which will let you check to see if the cast succeeded or not.
  • static_cast will let you cast to something below you in your inheritance tree, but you lose the ability to check if it succeeded.
  • You could also throw caution to the wind completely and use a C-style cast.

Upvotes: 2

znkr
znkr

Reputation: 1756

Short answer: You cannot. Because your compiler does not know what pb is. it could be of type A. However, you an use dynamic_cast, which returns a B pointer or NULL if that is not possible.

A *pa = new B();
B *pb = dynamic_cast<B*>(pa);
if (pb) {
    pb->data = 10;
}
else {
    ...
}

Anyhow, if you need to do that it probably means that you should revise your design as upcasting is not a good idea. Sometimes though, you just cannot avoid it. E.g. when using external libraries and such.

Upvotes: 1

littleadv
littleadv

Reputation: 20262

The need points to a faulty design.

But if you really insist writing bad code, you can just cast back to B *.

Upvotes: 2

Related Questions