Search code examples
c++castinguser-defined-types

casting object with user defined type


Can we cast an object with user-defined types, like we do for normal data types? Like say we do type cast for int like:

int variable_one = (int)variable_name;

So can we do like: (complex) object_name; where complex is the class I have written for complex number addition using operator+ overloading.

Is it possible in this normal way? Or do we need to write some function before calling this statment? Or is it not possible at all to type-cast like this?


Solution

  • int variable_one=(int)variable_name; is a C style cast.

    C++ offers many casting operators:

    • dynamic_cast <new_type> (expression)
    • reinterpret_cast <new_type> (expression)
    • static_cast <new_type> (expression)
    • const_cast <new_type> (expression)

    Have a look at article about type casting or refer to any C++ introductory book.