Home > Back-end > Virtual functions of polymorphic inheritance run results as follows, please explain
Virtual functions of polymorphic inheritance run results as follows, please explain
Time:10-07
# include "StdAfx. H" #include #include #include using namespace std;
If # 1 Class A { Public: Void foo () { Printf (" 1 \ n "); } Virtual void fun () { Printf (" 2 \ n "); } }; Class B: public A { Public: Void foo () { Printf (" 3 \ n "); } Void fun () { Printf (" 4 \ n "); } }; Int main (void) { A, A. B B; B * PTR=NULL; PTR=(B *) & amp; a; PTR - & gt; Foo (); PTR - & gt; Fun (); getchar(); return 0; } As application, operation results for 3 2 Don't understand why there are such result, strives for the great god
CodePudding user response:
Very magical, unexpectedly someone so using polymorphism,
The correct method is: A * PTR=& amp; B; P - & gt; Fun ();
CodePudding user response:
You use methods are dangerous, can turn a subclass object when the superclass object to make, don't put the superclass object when a subclass object,
CodePudding user response:
I know the correct method of use is A * PTR=& amp; B; P - & gt; Fun ();
Now just want to know why the result is Why B * PTR=(B *) & amp; a; PTR - & gt; Call to the derived class method foo, and PTR - & gt; Fun () calls to the base class method