Popgalop
Popgalop

Reputation: 757

Cast base class object to derived class

Lets say I have two classes, animal and dog like this.

class Animal
{

};

class Dog : public Animal
{

};

And I have an animal object named animal, that is actually an instance of dog, how would I cast it back to dog? This may seem like an odd question, but I need it because I am writing a programming language interpreter, and on the stack everything is stored as a BaseObject, and all the other datatypes extend BaseObject. How would I cast the base object from the stack, to a specific data type? I have tried something like this

Dog dog = static_cast<Dog>(animal);

But it gives me an error

1>------ Build started: Project: StackTests, Configuration: Debug Win32 ------
1>  StackTests.cpp
1>c:\users\owner\documents\visual studio 2012\projects\stacktests\stacktests\stacktests.cpp(173): error C2440: 'static_cast' : cannot convert from 'Animal' to 'Dog'
1>          No constructor could take the source type, or constructor overload resolution was ambiguous
1>c:\users\owner\documents\visual studio 2012\projects\stacktests\stacktests\stacktests.cpp(173): error C2512: 'Dog' : no appropriate default constructor available
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Edit: I have decided to use pointers instead.

Upvotes: 0

Views: 4129

Answers (1)

Mark PM
Mark PM

Reputation: 2919

Use dynamic_cast:

Animal& animal = getAnimalFromStack();    
if(Dog *d = dynamic_cast<Dog*>(&animal)) 
    {
       // You have a dog pointer, use *d ...

    }

Upvotes: 1

Related Questions