Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of IsA() in C++?

I'm trying to figure out why some code bases use IsA() to determine object polymorphism if in C++ you can already safely upcast and down cast (using dynamic_cast) ?

So far the only case I see useful is when you are integrating a a scripting environment that is linked to the c++ codebase?

Thanks!

like image 269
Setheron Avatar asked Dec 06 '22 00:12

Setheron


2 Answers

There are few reasons where and IsA() function, or even a dynamic_cast<>() are needed in C++. The worst examples of this type of code are the giant if-then statements using dynamic_casts, or switch statements on a type field. These represent a maintenance nightmare, where adding a class can involve updating dozens, or hundreds of different locations to support the new class.

For example:

Bad:

// Don't do this:
void PrintName(Base *b, ostream &o)
{
   if (dynamic_cast<DerivedA *>(b) != NULL)
      o << "Derived A";
   if (dynamic_cast<DerivedB *>(b) != NULL)
      o << "Derived B";
   if (dynamic_cast<DerivedC *>(b) != NULL)
      o << "Derived C";
}

Better:

void PrintName(Base *b, ostream &o)
{
   o << b->GetName();
}

This is obviously eliding checking for null, and using smart pointers, etc.. Likewise, if you're querying the type to choose between different behaviours, you need to ask why you're doing something different for each type, and move that behaviour decision into the object.

Bad:

// Don't do this:
void ObjectBase::ApplyForceToObject(const Force &f)
{
    if (dynamic_cast<Wall*>(this) != NULL
        || dynamic_cast<Floor*>(b) != NULL)
    {
        // Do nothing
    }
    else
    {
        // Accelerate object
    }
}

Better:

void ObjectBase::ApplyForceToObject(const Force &f)
{
    if (IsFixedObject())
    {
        // Do nothing
    }
    else
    {
        // Accelerate object
    }
}
...
bool ObjectBase::IsFixedObject() { return false; }
bool Wall::IsFixedObject() { return true; }
bool Floor::IsFixedObject() { return true; }
like image 98
Eclipse Avatar answered Dec 09 '22 14:12

Eclipse


In modern C++ there is no point.

Frameworks dating from before the 1998 standardization may offer an IsA function.

E.g. as I recall there is such functionality in MFC.

Also, as you note, when dealing with objects implemented in other languages (with types not represented by C++ types) it may conceivably be useful.

Cheers & hth.,

like image 28
Cheers and hth. - Alf Avatar answered Dec 09 '22 14:12

Cheers and hth. - Alf