C++: Cast const reference of Base class to derived class

时间:2017-06-12 16:51:29

标签: c++ inheritance

I am trying to get my Base class instance and cast it to the derived class type. Since I can only get a const reference of my base class instance, I struggle to get it cast correctly. Does anyone have an idea?

class Base
{

};

class Derived : public Base
{

};

Base someBaseInstance;
const Base& GetBase()
{
    return someBaseInstance;
}

int main()
{

    Derived& derived = static_cast<Base&>(GetBase());
    return 0;
}

1 个答案:

答案 0 :(得分:0)

您必须将您的实例声明为Derived对象。它可以作为Base引用和传递,但必须声明为Derived

Derived someDerivedInstance;

另外,要在BaseDerived之间进行转换,您应该使用dynamic_cast<>

Derived &derived = dynamic_cast<Derived&>(GetBase());