Saturday, May 22, 2010

C++ / polimorphism problem?

I have a base class and derived class like this ;





class base{


public :


int b;


virtual void x()=0;


}





class derived:public base{


public:


int d;


void x(){}


}





I define a pointer of base class :


base *p=new derived;





Here is my problem :


I know that I can access to b and x but how can I access to d .


I want something that help me to store data in d with this pointer and read from it (something like p-%26gt;d=12; )

C++ / polimorphism problem?
Since p doesn't know anything about derived, it doesn't have any access to d. There are several ways to get around this, but perhaps the best is something like this:





derived *dPtr = dynamic_cast%26lt;derived%26gt;(p); // cast base to derived


if (dPtr) // if cast succeeded


dPtr-%26gt;d = 12;


No comments:

Post a Comment