简体   繁体   中英

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.

Use dynamic_cast:

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

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM