c++ - Is this a valid downcasting -


i have cpp code in class c derived class b , class b derived class a.

now class b has public data member. creating instance of class c on heap passing pointer class pointer , there downcasting pointer pointer of class b , printing public variables of class b.

is valid downcasting. asking because change of compiler has broken working code.

i including below code snippet captures problem having.

#include <iostream> using namespace std;   class grand { }; class parent : public grand {     public : parent(){i=0;}     int i;     parent(int j){ = j;}     void set(int j){i = j;} };  class child : public parent{   public: child(){}; };  void print ( grand* ptr) {     parent *p = (parent*) ptr;     std::cout << std::endl << p->i << std::endl; }  int main() {     // code goes here     child c;     c.set(9);     print(&c);     return 0; } 

thanks

is valid downcasting.

yes. cast internally applies static_cast, which, according §5.2.9/11, give right result. if argument ptr doesn't point parent, result of cast undefined - , execution of following code be.

downcasting of polymorphic types in c++ works via dynamic_cast. grand class above isn't polymorphic - have add @ least virtual destructor grand make polymorphic. otherwise you'll compiler error following code.

parent *p = dynamic_cast<parent*>(ptr); // once grand polymorphic... 

and check whether result, p, non-zero. method reveals (at runtime) whether cast worked! others either invoke undefined behavior or undefined, non-zero values.

some notes:

  • downcasting sign of bad design. avoid if possible, using - example - virtual (print) functions.
  • print should take pointer const since doesn't modify data members.

Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

android - Associate same looper with different threads -

visual studio 2010 - Connect to informix database windows form application -