Reputation: 1916
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
Reputation: 5470
Without virtual functions the only thing you could do is downcast it. There's a few ways to go about that:
Upvotes: 2
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
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