3.1 Up casting

Up casting refers to a cast from a subclass type to a superclass type. Observe the following example:

class A
{
  // definitions
};

class B : public A
{
  // definitions
};

Given this definition, we can perform two types of up casting. The first one deals with pointers, whereas the second one deals with references.

B myB;
A &rMyA(static_cast<B&>(myB));

In this example, rMyA becomes a reference to myB. However, rMyA only has access to the class A members.

We can also cast pointers:

B myB;
A *pMyA = static_cast<A*>(&myB);

In this example pMyA becomes a pointer to myB. Again, pMyA only has access to the class A members.

A static up cast can be implicitly done, like in the following code (assuming that class B is derived from class A):

{
B myB
A *pA;

pA = &myB;
}



Copyright © 2006-10-12 by Tak Auyeung