If you attempt a dynamic cast from a non-polymorphic type, you will also get a compile-time error. For example:

class Base {

// class details omitted

};

class Derived : public Base { // class details omitted

};

int main()

{

Base *p; Derived *q;

Base b; p = &b;

q = dynamic_cast<Derived *> (p);

}

The above generates a compile-time error:

Dynamic down-casts and cross-casts must start from a polymorphic class (one that contains or inherits a virtual function); but class Base is not polymorphic.

The syntax of conditions allows declarations in them. For example:

class Base {

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

};

class Derived : public Base { public:

void derivedFunction();

// other class details omitted

};

void Base::f()

{

// Define Base function.

}

void Derived::derivedFunction()

{

}

int main()

{

Base *p = new Derived;

//

details omitted

 

 

if

(Derived *q = dynamic_cast<Derived *>

(p))

 

q->derivedFunction();

// use

derived function

}

You can use dynamic casts with references as well. Since a reference cannot be zero, when the cast fails, it raises a Bad_cast exception. Before the implementation of the dynamic cast operator, you could not cast from a virtual base class to one of its derived classes because there was not enough information in the object at runtime to do this cast. Once runtime type identification was added, however, the information stored in a polymorphic virtual base class is sufficient to allow a dynamic cast from this base class to one of its derived classes. For example:

140 Standardizing Your Code