jeudi 15 juillet 2021

DerivedA pointer pointing to DerivedB

I have a base class which serves as an interface (if I use that word correctly). The idea is that the base class has some derived classes that implement one virtual function of the base class. Then I also need another class who extends the base class (lets call it extended base). What I would like is that I can store a class derived from base into an extended base pointer.

MWE:

class Base {
public:
    virtual ~Base();
    virtual double value();
}
class Derived : public Base{
public:
    double value() override {return 5;}
}
class ExtendedBase : public Base {
public:
    virtual ~ExtendedBase ();
    virtual double value2(){return 10;}
}

int main() {
    ExtendedBase * object;
    object = new Derived();
    std::cout << object->value(); //should give implementation in Derived, i.e. 5
    std::cout << object->value2(); //should give implementation in ExtendedBase, i.e. 10
    delete object;
    return 0;
}

With this MWE I get a compile error at the second line in the main. error: cannot convert 'Derived*' to 'ExtendedBase*' in assignment object = new Derived();. Part of me understands why it doesn't work (although I can't explain), but I would like to know if I can get the desired behaviour in some other way.

P.S. Sorry about the bad question name, I couldn't think of another way to keep it short

P.S.2 I know raw pointers like this are not advised. In the future I will change to smart pointers but I don't think there are needed for this simple example

Aucun commentaire:

Enregistrer un commentaire