Apologies if this is sort of vague, but I don't know how to go about code reuse in the following situation. I'm using C++.
The program is a simple simulation and it has a few different things in play.
struct StupidBug;
struct SmartBug;
struct Plant;
struct Mammal;
Each of these things have a set of things they are capable of.
struct StupidBug
{
// Can walk,
// Can eat,
// Can see surroundings,
// Can spawn,
};
struct SmartBug
{
// Can walk,
// Can eat,
// Can see surroundings,
// Can see extended surroundings,
// Can spawn,
};
struct Plant
{
// Can spawn
// Can see surroundings
};
struct Mammal
{
// Can walk,
// Can eat,
// Can see surroundings,
// Can see extended surroundings,
};
There is quite a bit of overlap in functionality between these lifeforms but I don't know how to go about sharing the code between them. I can't think of any suitable form of inheritance for all of these. I tried composition, doing something along the lines of:
struct AbilityToWalk
{
void walk(position, direction)
{
// walk code
}
};
struct StupidBug
{
AbilityToWalk walk;
// other abilities
};
struct SmartBug
{
AbilityToWalk walk;
// other abilities
};
// etc...
But the walk function relies on the position of whatever is calling it. It felt odd passing the position of a lifeform to it's own member function, and overall felt like a very clumsy solution.
I'm not sure how to go about dealing with this situation. Is there a way to do this that is intuitive and elegant? Am I missing something fairly obvious?