Casting in C++.


  • What is Casting in the view point of Class ?
Casting is the process of accessing methods of a class with a pointer to another class within the same class hierarchy.
  1. In a class hierarchy, a pointer to the base class can be used to call the implementation of base class virtual
    methods residing in the derived class object
    . Since the derived class contains the definitions of all the base
    classes from which it is derived, it is safe
    to cast a pointer up in the hierarchy to any of the parent (or base)
    classes.
    This is called upcasting because the pointer is moved up in the class hierarchy.
  2. Upcasting is usually typesafe, thus the base classes are subsets within the vtable of the derived class.
  3. If we try to access the derived class methods using a pointer to one of its parent (or base) class objects, we
    are downcasting the pointer because we are moving the pointer
    down in the class hierarchy. Since
    downcasting involves accessing methods
    not defined in the base class vtable, the object we are trying to ca
    st should
    be of the correct type for the casting to be safe.
  • C++ provides different casting operators for different situations.
    • Dynamic Casting
      • Operator is used to perform the upcasting and downcasting within the hierarchy.
      • Perform the run-time check to make the operation safe.
      • Perform on the ambiguous conversion and it will fail by returning of NULL in case of pointer cast or by throwing a bad_cast exception in case of reference cast.
      • dynamic_cast< T >(experssion);
    • Static Casting
      • Operator is Used for Non-Polymorphic type conversion, such as enum to int, int to float, and so on.
      • Static Casting doesn't perform a run-time checking to ensure safe casting.
      • Operator is used in situation where you are certain that the expression of casting is really an object of the appropriate type.
      • Operator is used in situation where you are certain the the conversion is not going to fail.
      • If conversion fail, it will just return, as if nothing went wrong.
      • static_cast< T >(expression);
    • Const Casting
      • Operator must be used to add or remove the const and the volatile from identifiers.
      • Example:
        Const Casting Example

    • Reinterpret Casting

posted on 2008-02-04 11:43  Morris  阅读(453)  评论(0编辑  收藏  举报

导航