class parent definition.
data pub_parent type i.
class child definition inheriting from parent.
data pc type i.
data parent type ref to parent.
data child type ref to child.
data child1 type ref to child.
create object child.
create object parent.
parent ?= child.
code snippet above doesnt gives me any error..I am doing narrow casting here with a widening cast operator ?=.does that mean ,when it comes to narrow casting u can use either = or ?=.it doesnt make any difference?
Suhas Saha replied
I'll try to explain this using an example.
DATA: go1 TYPE REF TO object, "More generic go2 TYPE REF TO zcl_myclass. "Less generic
When you try to assign a 'more-generic' ref. to a 'less generic' ref., the static check performed by the compiler throws a compilation error.
* Assign a more generic ref. to less generic ref. go2 = go1.
The compiler checks the static types of go1 & go2 and since the assignment is not compatible(more generic is being assigned to less generic) syntax error is raised.
The casting operator '?=' is a kind of instruction to the compiler to skip the static check & perform the checks during runtime!
CREATE OBJECT go1 TYPE zcl_myclass. TRY . * Static compiler check is skipped. The compatibility is checked only * at runtime go2 ?= go1. MESSAGE 'Casting is successful' TYPE 'S'. CATCH cx_sy_move_cast_error. MESSAGE 'Error in casting' TYPE 'E'. ENDTRY.
The compiler checks the type of go1 at runtime & since the assignment is compatible no exception is raised.
Consider this example, the exception CX_SY_MOVE_CAST_ERROR is raised at runtime since the dynamic types are not compatible!
DATA: gx_err TYPE REF TO cx_sy_move_cast_error, gv_msg TYPE string. CREATE OBJECT go1 TYPE zcl_airlines. TRY . * Static compiler check is skipped. The compatibility is checked only * at runtime go2 ?= go1. MESSAGE 'Casting is successful' TYPE 'S'. CATCH cx_sy_move_cast_error INTO gx_err. gv_msg = gx_err->get_text( ). MESSAGE gv_msg TYPE 'S'. ENDTRY.
But i could use the ?=,operator for assigning a less_gen to a more_gen ref.variable.why?
The casting operator '?=' can be used for both narrowing as well as widening cast. But in case of widening cast, its use is redundant.
Hope you get my point.
Edited by: Suhas Saha on Jun 13, 2011 5:16 PM