Friday, July 31, 2009

Polymorphism query:In C++ can a method of a derived class be called using the pointer of the base class?

The method is not declared in the base class..


It is only defined in the derived class

Polymorphism query:In C++ can a method of a derived class be called using the pointer of the base class?
Only if you cast the pointer to be a pointer to the derived class. You can use the dynamic_cast operator to do this.





DerivedClass *pDerived = dynamic_cast%26lt;DerivedClass %26gt;(pBase);





pDerived-%26gt;FcnInDerivedClass();
Reply:no you can't.becouase:


class a


{


};


class b:public class a


{


int b;


int getdata()


{


return b;


}


};


void main()


{


a *pa=new a;// it is 0 byte.


b *pb=*(%26amp;pa);


cout%26lt;%26lt;pb-%26gt;getdata(); // getdata try to access unhandled memory


}

elephant ear

No comments:

Post a Comment