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
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