简体   繁体   中英

why compiler complains cannot initialize “Derived” with an rvalue of type Base

class Base {
public:
    virtual Base* clone() const { return new Base(*this); }
    // ...
};
class Derived: public Base {
public:
    Derived* clone() const override { return new Derived(*this); }
    // ...
};
int main() {
    Derived *d = new Derived;
    Base *b = d;
    Derived *d2 = b->clone();
    delete d;
    delete d2;
}

i compile above code in the latest version of Xcode, and compiler complains

cannot initialize a variable of type "Derived*" with an rvalue of type "Base*"*

at Derived *d2 = b->clone() .

But I already make clone virtual and let the clone() in Derived return Derived * .

Why do I still have such problem?

The return type of Base::clone() is Base* , not Derived* . Since you are invoking clone() through a Base* , the expected return value is a Base* .

If you invoke clone() through a Derived* , you will be able to use the return type of Derived::clone() .

Derived *d = new Derived;
Derived *d2 = d->clone();   // OK

Also,

Base *b = d;
Derived *d2 = dynamic_cast<Derived*>(b->clone());  // OK

Also,

Base *b = d;
Derived *d2 = dynamic_cast<Derived*>(b)->clone();  // OK

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