b=false; // Set it to false.

}

dynamic_cast Keyword

The keyword dynamic_cast is used in expressions to check the safety of a type cast at runtime. It is the simplest and most useful form of runtime type identification. You can use it to cast safely within a class hierarchy based on the runtime type of objects that are polymorphic types (classes including at least one virtual function). At runtime, the expression being cast is checked to verify that it points to an instance of the type being cast to.

Usage

A dynamic cast is most often used to cast from a base class pointer to a derived class pointer in order to invoke a function appearing only in the derived class. Virtual functions are preferred when their mechanism is sufficient. Usually a dynamic cast is necessary because the base class is being specialized, but cannot (or should not) be modified.

Example

class Base {

virtual void f(); // Make Base a polymorphic type. // other class details omitted

};

class Derived : public Base { // class details omitted

};

void Base::f()

{

// define Base function

}

int main()

{

Base *p; Derived *q;

Base b;

Derived d;

p =

&b;

 

 

 

 

 

q =

dynamic_cast<Derived *>

(p);

// Yields

zero.

 

p

=

&d;

 

 

 

 

 

q

=

dynamic_cast<Derived *>

(p);

//

Yields

p treated

 

 

 

 

//

as a derived

pointer.

}

Static and dynamic casts are used to move within a class hierarchy. Static casts use only static (compile-time) information to do the conversions. In the example above, if p is really pointing to an object of type Derived, either a static or dynamic cast of p to q yields the same result. This is also true if p were the null pointer. But, if p is not pointing to an object of type Derived, a dynamic cast returns zero, and a static cast returns a stray pointer. Dynamic casts must be done to a pointer or reference type. For example, if the cast above is written as:

q = dynamic_cast <Derived> (p);

The compile time error message is:

The result type of a dynamic cast must be a pointer or reference to a complete class; the actual type was Derived.

HP aC++ Keywords 139