When using dynamic_cast in Visual C++ 6.0

Dynamic cast is normally used to cast an object of derived type to the base type when the classes are polymorphic type (they contain virtual functions and method over riding).

#include <assert.h>

class CBase

{

public:

virtual ~CBase();

virtual void MyFunction() { cout<<“Base”; }

};

class CDerived : public CBase

{

public:

~CDerived();

void MyFunction() { cout<<“Derived”; }

};

int main()

{

CBase* Base = new CDerived();

CDerived* Derived = dynamic_cast<CDerived*>(Base);

assert(Derived);

delete Base;

return 0;

}

Although the code is perfectly legal, in VS 6.0, the compiler will throw a warning

“dynamic_cast’ used on polymorphic type ‘class CBase’ with /GR-; unpredictable behavior may result”.

And if you ignore the warning and run the program, you will get an exception thrown at the line of dynamic cast.

This is because the VC++ 6.0 compiler is not using the feature of Runtime type Information (RTTI).
To enable RTTI, go to Project–>Settings–>C/C++ and in the Category combo box, select C++ Language. Now enable the check box “Enable Runtime type Information (RTTI)”.

Now compile the program and run it.

If you call Base->Myunction() and Derived->MyFunction(), you will get result as “Derived” and it is quite expected.

If you try to dynamic cast a base class to derived class, with the above option, the compiler won’t show any warning, but the result will be NULL. (Note the assert statement in the code). So be careful to cast only the right type.

Instead, if you use the following code snippet,

CBase* Base = new CBase();

CDerived* Derived = static_cast<CDerived*>(Base);

assert(Derived);

Base->MyFunction();

Derived->MyFunction();

delete Base;

the code will compile and run successfully. But the result will be “Base” for both calls.

static_cast does not employ any kind of run time type checking.

dynamic_cast has that overhead, but it is safer.

Advertisements

2 Responses to When using dynamic_cast in Visual C++ 6.0

  1. Sky says:

    It helps, thank you

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: