mardi 2 juillet 2019

Saving abstract value object in wrapper and Usage of inheritance

I have issues regarding C++ class inheritance. I have a class which has virtual method, for example:

class IFoo {
public:
    virtual int sayFoo() = 0;
};

And I have several implementations, for example:

class Foo1: public IFoo {
public:
    virtual int sayFoo() {
        return 1;
    }
};

class Foo2: public IFoo {
public:
    virtual int sayFoo() {
        return 2;
    }
};

I want to hold IFoo instance inside a dummy container class (like a sort of wrapper) exposing the same interface of IFoo:

class DummyWrapper : public IFoo {
public:
    DummyWrapper(IFoo& foo): foo{foo} {}
    virtual int sayFoo() {
        return foo.sayFoo(); //ALPHA
    }
private:
    IFoo& foo; //BETA
};

Normally everything should work, for example, like this:

IFoo& foo = Foo1{};
DummyWrapper wrapper{foo};

wrapper.sayFoo();

My problem is that foo is actually just a r-value that is removed after its scope goes out, like here:

DummyWrapper generateWrapper() {
    return DummyWrapper{Foo1{}};
}

This lead to read problems in "ALPHA" line. A solution would be to put the r-value on the heap and use pointers to access the foo. Since I'm new to C++ and maybe I'm falling into a XY problem, my question is:

  • is this the only solution? Isn't there a better method to use to solve the issue?
  • I don't think i can replace "BETA" line with IFoo foo since in this way the DummyWrapper will always store the bytes of a IFoo, not of a IFoo implementation. Or maybe I can use the value IFoo foo to call derived virtual methods?

Thanks for any kind reply

Aucun commentaire:

Enregistrer un commentaire