简体   繁体   中英

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.

The need points to a faulty design.

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

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.

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. Eg when using external libraries and such.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM