How To Use Dynamic Cast

March 31, 2008

Eventhough I would suggest avoiding any type of casting, there are not many situations in C++ where you can omit them. Among the casts, dynamic cast can be very handy and is a normally used one. It is used to convert objects of one type to another related (as a result of inheritance) type.

Eg:

class CMyClass

{

virtual void Foo()

{

}

};

class CMyDerivedClass : public CMyClass

{

void Foo()

{

}

} ;

// Declare a variable of

CMyDerivedClass* myDerivedClassObject = new CMyDerivedClass();

// Call Foo() of derived class

myDerivedClassObject->Foo();

// Call Foo() of the base class

CMyClass* myClass = dynamic_cast<CMyClass*>(myDerivedClassObject);

// Make sure that our program won’t crash

assert(myClass);

myClass->Foo(); // Calls the Foo() in the base class

Note the assert statement. It is always a good practice to use assert just after the dynamic cast, to make sure that you are not going to access an uninitialized object.

Advertisements

ASSERT and VERIFY in VC++

March 31, 2008

Both these are used to make sure that an expression or statement in VC++ is executed properly.

In the debug version, both have no difference at all. But if you compile these statements in the release version, the one with ASSERT won’t be executed at all, but the one with VERIFY will work normally.

Eg:

CString StrMyString(“This is my string”);

ASSERT ( StrMyString.Erase(0,2));

will not cause the first two characters to be erased, if compiled in the release version.

But

VERIFY (StrMyString.Erase(0,2)) ;

will cause the first two characters to be erased.