C ++ polymorphism ((X *) y) & # 8594; foo () vs ((X) * y) .foo ()

Suppose Y is a derived class from class X, and X declares foo virtual. Let y be of type (Y *). Then ((X *) y) → foo () will execute the Y version of foo (), but ((X) * y) .foo () will execute the X version. Can you tell me why polymorphism is not applied in case of dereferencing? I expect any syntax to give a version of Y foo ().

+5
source share
5 answers

You cut a part of the object Yand copy the object to the object X. The called function is called on the object X, and therefore the function is called X.

++ , , casted-to , .

, X ( , , X, , Y),

((X&)*y).foo()

Y X.

  • Y, Y*. lvalue Y. lvalue , .
  • X&, X. lvalue X.
  • .

  • Y.
  • X. X. rvalue X. X, rvalue.
  • .
+10

(*) , , , .

X * ( X *). , y, Y.

X X. *y, . foo() "" , , y.

, , , : X, , , X. X, X, . .

(*), , . foo().

+8

( *y) , cast ( (X)) () X - , . , X - , , Y (, X ctor, , ?), , - Y - , this Y, ... !

, , , : *X , Y*, Y (, Y, ).

, ctor , - ; . , Haahr : " "... Java, , , ++ ( ctor "cuticing" )!)

+2

, - , . , , , . ( ), , , ++.

0

, , , ++ :

(X) * y X. sizeof (X) , Y, , foo(), X-. , Y.

The code (X *) y is like creating a pointer to an object, and the compiler knows that the specified object is X or a subclass of X. At run time, when you look up the pointer and call foo using "-> foo ()", the object class is defined and the correct function is used.

0
source

All Articles