downcast problem in c++ -


#include <iostream> using std::cout; using std::endl; class base { public :     void f();     void g();      int mbasedata1;  };  class derived : public base { public :        int mderiveddata1; };  void main() {      base* base = new base();     derived* derived = (derived*)(base); // downcast     derived->mderiveddata1 = 6;     cout<< derived->mderiveddata1<<endl; // result = 6; } 

in code new base() allocate memory in heap

and derived* derived = (derived*)(base) cast base derived

how can use mderiveddata1? cant find allocate memory mderiveddata1 or when call constructor of derived allocate mderiveddata1 ?

the reason can't find memory mderiveddata1 allocated because no memory allocated. have performed invalid type-cast. thing stored in base pointer base instance. using type-cast tell compiler it's pointer derived instance doesn't make (but compiler believe anyway because you're 1 in charge). object still base. if want derived, you'll need instantiate derived. can use dynamic_cast convert base pointer derived pointer.

base* base = new derived; derived* derived = dynamic_cast<derived*>(base); derived->mderiveddata1 = 6; 

Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

aspxgridview - Devexpress grid - header filter does not work if column is initially hidden -

c# - How to execute a particular part of code asynchronously in a class -