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 ().
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.
Y
X
++ , , casted-to , .
, X ( , , X, , Y),
((X&)*y).foo()
Y X.
Y*
X&
(*) , , , .
X * ( X *). , y, Y.
y
X X. *y, . foo() "" , , y.
*y
foo()
, , , : X, , , X. X, X, . .
(*), , . foo().
( *y) , cast ( (X)) () X - , . , X - , , Y (, X ctor, , ?), , - Y - , this Y, ... !
(X)
this
, , , : *X , Y*, Y (, Y, ).
*X
, ctor , - ; . , Haahr : " "... Java, , , ++ ( ctor "cuticing" )!)
, - , . , , , . ( ), , , ++.
, , , ++ :
(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.