Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Put members in common for two sub classes

Let a library containing the following class hierarchy :

class LuaChunk
{
};

class LuaExpr : public LuaChunk
{
};

class LuaScript : public LuaChunk
{
};

Now I would like to use this library in my application by extending these two classes :

class AppLuaExpr : public LuaExpr
{
private:

    Foo * someAppSpecificMemberFoo;
    Bar * someAppSpecificMemberBar;
};

class AppLuaScript : public LuaScript
{
private:

    Foo * someAppSpecificMemberFoo;
    Bar * someAppSpecificMemberBar;
};

The problem here is that, if I have many members, each of them having its own pair of getter/setter, it's going to generate a lot of code duplication.

Is there a way, that does not use multiple inheritance (which I want to avoid) to put in common the application-specific stuff contained in both AppLuaExpr and AppLuaExpr ?

I've taken a look on the existing structural design patterns listed on Wikipedia, but it doesn't seem like any f these is adapted to my issue.

Thank you.

like image 582
Virus721 Avatar asked Mar 15 '16 10:03

Virus721


1 Answers

You could express the common data as their own class and pass that during construction. That way you can encapsulate everything using composition.

class Core { }; 

class Component { 
    int one, two;
public:
    Component(int one, int two) : one(one), two(two)
    {}
};

class Mobious : public Core 
{
    Component c;
public:
    Mobious(Component &c) : Core(), c(c) { }
};

class Widget : public Core
{
    Component c;
public:
    Widget(Component &c) : Core(), c(c)
    {}
};

int main(void)
{
    Widget w(Component{1, 2});
    Mobious m(Component{2, 3});;
    return 0;
}
like image 126
Johannes Avatar answered Oct 14 '22 04:10

Johannes