Cast base class object to derived class

Posted by Popgalop on Stack Overflow See other posts from Stack Overflow or by Popgalop
Published on 2013-10-22T21:40:54Z Indexed on 2013/10/22 21:53 UTC
Read the original article Hit count: 169

Filed under:
|

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 ==========

© Stack Overflow or respective owner

Related posts about c++

Related posts about casting