Alex
Alex

Reputation: 876

dynamic cast with inheritance hierarchies

so I have this code:

Base* objbase = new Derived();

//perform a downcast at runtime with dynamic_cast
Derived* objDer = dynamic_cast<Derived*>(objBase);

if(objDer)//check for success of the cast
    objDer->CallDerivedFunction();

This is a snippet of code for a cast operators section in my book.

Now why do I have this, I don't understand what's the point of having to dynamically cast a pointer to a base object pointing to a Derived object; For me, that's something to do with polymorphism giving us the ability to do objBase->DeriveClassFunction(), but I don't really know.

In the first place why does it do this: Base* objbase = new Derived();, and then why does it cast a base object pointer to a Derived again, I can't quite figure out why.

Thanks in advance.

Upvotes: 0

Views: 86

Answers (1)

Bizzarrus
Bizzarrus

Reputation: 1329

That code snippet is just a demonstration of what's possible. It describes a tool, what you do with this tool is up to you. A slightly bigger example might be:

class Animal {
    void Feed();
};
class Cat : public Animal { /*...*/ };
class Dog : public Animal {
    // Only dogs need to go out for a walk
    void WalkTheDog();
};

void Noon(Animal* pet)
{
    // No matter what our pet is, we should feed it
    pet->Feed();

    // If our pet is a dog, we should also take it out at noon
    Dog* dog = dynamic_cast<Dog*>(pet);
    if(dog) // Check if the cast succeeded
        dog->WalkTheDog();
}

Noon(new Cat()); // Feed the cat
Noon(new Dog()); // Feed the dog and take him out

Notice that every animal has the Feed() function, but only dogs have the WalkTheDog() function, so in order to call that function, we need to have a pointer to a dog. But it would also be quite a waste to copy the Noon() function for both types, especially if we might later add even more animals. So instead, the Noon() function works for any kind of animal, and does only the dog-specific things only if the animal is actually a dog.

Upvotes: 2

Related Questions