C++ simple polymorphism issue -


ok admit it, i'm total c++ noob.

i checking book data structures , algorithms in c++ adam drozdek, in section 1.5 : "polymorphism" proposes next example:

class class1 { public:     virtual void f()     {         cout << "function f() in class1" << endl;     }      void g()     {         cout << "function g() in class1" << endl;     } };  class class2 { public:     virtual void f()     {         cout << "function f() in class2" << endl;     }      void g()     {         cout << "function g() in class2" << endl;     } };  class class3 { public:     virtual void  h()     {         cout << "function h() in class3" << endl;     } };  int main() {     class1 object1, *p;     class2 object2;     class3 object3;      p = &object1;      p->f();     p->g();      p = (class1*)&object2;     p->f();     p->g();      p = (class1*)&object3;     p->f();    // abnormal program termination should occur here since there                 // no f() method  in object3, instead object3->h() called     p->g();     //p->h();   h() not member of class1      return 0; } 

i compiled using visual studio 2010, , 2 things happened:

  1. first there no "abnormal termination" in line p->f()
  2. the method h() of object3 called in line "abnormal termination" should occur.

the output of programs is:

function f() in class1 function g() in class1 function f() in class2 function g() in class1 function h() in class3 function g() in class1

i´m trying understand why happens, seems strange me.

any great.

thanks in advance!

if that's code book uses, throw book in trash immediately. polymorphism works on inheritance, such as

class class2 : public class1 

without that, there no hope of correct program.

the author appears try , circumvent requirement (i.e., incorrect program compile) using

p = (class1*)&object2; 

this c-style cast, , interpreted c++

p = reinterpret_cast< class1 * >( &object2 ); 

reinterpret_cast dangerous operator, , should never used between 2 polymorphic types. should used:

// use if dynamic type of object2 same static type: p = static_cast< class1 * >( &object2 ); // not compile unless add : public class1 

or

// returns null if object2 dynamic type not derived class1 p = dynamic_cast< class1 * >( &object2 ); 

as "abnormal termination", think author describing how code crashed on machine. however, that's not because language says should. wrote incorrect program, may crash on machines not others.


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -