OOPS - [C++ Type Conversion]

♠ Posted by Unknown in at 10:00

Type Cast Operator


C++ permits explicit type conversion of variable or expressions using the type case operator.

Traditional C casts are augmented in C++ by a function-call notation as a syntactic alternative. The following two versions are equivalent.

                        (type-name) expression; //C notation
                        type-name (expression); //C++ notation

Examples:
                        average = sum / (float) i; //C notation
                        average = sum / float (i); //C++ notation

A type name behaves as if it is a function. For converting values to a designated type the function call notation usually reads to simplest expressions. However, it can be used only if the type is an identifier.

                       p = int * (q);

is illegal, in such cases, we must use C type conversion.

                        p = (int *) q;

Alternatively, we can use “typedef “to create an identifier of the required type and use it in the functional notation.

                        typedef int * int_pt;
                        p = int_pt (q);

Ansi C++ adds the following new cast operators: 
  1. const_case
  2. static_cast
  3. dynamic_cast
  4. reinterpret_case

0 comments:

Post a Comment