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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With