why is casting from a base class object to derived class object is unsafe?please explain with examples

lets say you have a base class called Animal and two derived classes called Dog and Cat. Casting a pointer of type Animal to Dog is unsafe because that might actually be type Cat. If there is something about Animal that will tell you whether it is a Dog or not, then make the test and typecast only if the test passes.

Run the example below and you will see that the function foo() cast the pointer to the wrong type of object.

#include <iostream>
using std::cout;

class Animal
{
public:
    Animal() { nLegs = 4; }
    virtual void Speak() = 0;
protected:
    int nLegs;
};

class Dog : public Animal
{
public:
    Dog() {};
    virtual void Speak() { cout << "Wolf\n";}
};

class Cat : public Animal
{
public:
    Cat() {};
    virtual void Speak() { cout << "Meow\n";}
};

void foo(Animal* anm)
{
    Cat* pCat = reinterpret_cast<Cat*>(anm);
    pCat->Speak();
}

int main()
{
    Dog dg;
    foo(&dg);
}

To assure that the base class is pointing to the correct child class we use 'dynamic_cast' . This will do a RTTI to make sure that the base class is actually pointing to class to which it's being downcasted to.

To assure that the base class is pointing to the correct child class we use 'dynamic_cast' . This will do a RTTI to make sure that the base class is actually pointing to class to which it's being downcasted to.

Well, that certainly does work -- and it crashes the program at runtime when its the wrong type of object as illustrated in the code I posted above. Using try/catch block doesn't catch the exception either.

void foo(Animal* anm)
{
    try
    {
        Cat* pCat = dynamic_cast<Cat*>(anm);
        pCat->Speak();
    }
    catch(std::bad_cast)
    {
        cout << "Wrong cast\n";
    }
}

Then what's the solution? i read the post on dynamic case after i posted this and think i read that c-style casting can help avoid this, is that right?

c-style casting only hides the problem just like tye static_cast I attempted to use earlier. The dynamic_cast illustrated here works as it should because its not trying to cast up the chain. Microsoft Foundation Class (MFC) uses a pretty slick way to get around this, but I don't know its internal workings.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.