[Solved] Overriding CAST operator (i think it is called downcasting) [closed]


In C++ you can cast a pointer to a base type into a pointer to a derived type using dynamic_cast, assuming it pointed to the derived type in the first place.

class A
{
};

class B : public A
{
};

int main()
{
    A * a = new B();
    B * b = dynamic_cast<B*>(a);

    if( b == nullptr )
    {
        // Error - "a" was not a "B" object
    }

    return 0;
}

When you see (sometype)Object, in C++, that is a C-style cast, and is not the way to enlightenment. This is equivalent to a C++ reinterpret cast and can be quite dangerous. It certainly should not be used where a dynamic_cast is sufficient.

Also, in C++, when you have a polymorphic type, you must use a pointer. You would not cast an instance of an object, but rather, you would cast a pointer to the object.

Please Google both “dynamic_cast” and “reinterpret_cast” for a better understanding of both.

4

solved Overriding CAST operator (i think it is called downcasting) [closed]