Dynamic cast using c++
dynamic_cast() is more useful to find out what kind of object is pointed to by the given pointer.
This is used when you write a function that could accept any objects of the given class's hierarchy and then you take care of it inside the method.
Like,
function myMethod(Base *ptr) // can recognize any object that is of Base's family
{
if (dynamic_cast(ptr) != NULL) // the pointed-to object is of Child1
{
Child1 *myChild = ptr; // here you take care of it as it is of a Child1 object
// .. rest of the code
}
else if (dynamic_cast(ptr) != NULL) // the pointed-to object is of Child2
{
Child2 *myChild = ptr; // here you take care of it as it is of a Child2 object
// .. rest of the code
}
else if (dynamic_cast(ptr) != NULL) // the pointed-to object is of Child3
{
Child3 *myChild = ptr; // here you take care of it as it is of a Child3 object
// .. rest of the code
}
else {
// the object pointed-to by ptr is not Base's class family/hierarchy
// throw an error
}
Remember, in C++, a base class type pointer can recognize/works with its derived/child class object.
Considering the same, polymorphic rule, in above method/example, you can use the myMethod() to manipulate any of the derived objects of Base.
As noted earlier dynamic_cast<> allows you to (downcast) type-cast a class pointer safely to an object in one single family/hierarchy of classes. That is called safe downcasting.
In C++ a base class pointer can "recognize" or "identify" a derived object same family.
dynamic_cast<> "helps" you to identify what exactly a pointer pointed to an object of the same family, but "never said" a base pointer can access a member of derived object that is in fact not a part of base class.
For examle,
if (dynamic_cast(baseTypePtr) != NULL)
{
Derived1 *d1 = baseTypePtr;
//you can refer it via d1, as inside the content is actually a Derived1 type object
}
If you give:
Derived1 *dptr = new Dervied1();
Base *bptr = dynamic_cast(dptr);
result:
the bptr is set to null as dynamic cast returns a NULL as the object actually/currently pointed to by dptr is not of Base class type, in fact, it is of Derived1 type. So that you would not access a method which is not actualla a part of the pointed-to object.
In simple, dynamic cast helps you to "identify" the object actually a pointer points to so you would assign it to right type pointer and access right type methods.
It helps you downcast it safely not blindly.
if you give:
Base *bptr = (Base *) dptr; // c style casting, not safe at all, and possibly error
result:
run time error (with a possible compiler type warning)
Comments
Post a Comment
Please avoid link comments