OO Design -- where to put non-member functions - c++

I have a class with a complex construction process with many parameters. Multiple clients share objects of this class, and the union of these clients parameters are used to instantiate the class. Therefore I have a factory class that stores these requirements, checks consistency of the various clients' requests, and instantiates the class.
Additionally, there are a common set of use models (or sets of parameters) which multiple clients use for multiple factories.
For instance, consider an example. (Note that the actual code is C++, but my experience is in Python so I'll pseudo-code in Python. Yes, I know that this example wouldn't actually work as-is.)
class Classroom:
def __init__(self, room_size=None, n_desks=None, n_boards=None,
n_books=None, has_globe=False, ... ):
...
class ClassroomFactory:
def __init__(self):
self._requirements = dict()
def addRequirement(self, name, value):
if name.startswith("n_"):
self._requirements[name] = max(value, self._requirements.get(name, 0))
...
def createClassroom(self):
return Classroom(**self._requirements)
# instantiate the factory
factory = ClassroomFactory()
# "client 1" is a geography teaacher
factory.addRequirement("n_desks", 10)
factory.addRequirement("n_boards", 1)
factory.addRequirement("has_globe", True)
# "client 2" is a math teacher
factory.addRequirement("n_desks", 10)
factory.addRequirement("n_boards", 1)
# "client 3" is a after-school day-care
factory.addRequirement("room_size", (20,20))
factory.addRequirement("has_carpet", True)
room = factory.createClassroom()
The common use model is as a teacher, we need 10 desks and a board. I think this is best served by a non-member function/decorator, something like:
def makeTeacherRoom(factory):
factory.addRequirement("n_desks", 10)
factory.addRequirement("n_boards", 1)
return factory
This seems like a great example of the "prefer non-member/non-friend to member" paradigm.
The thing that I'm struggling with is, within the framework of a much bigger OO code, where should these types of non-member functions/decorators live, both in terms of namespace and in terms of actual file?
Should they live in the factory's file/namespace? They are closely related to the factory, but they're limitations on the general factory, and need not be used to use the factory.
Should they live in the client's file/namespace? The client understands these use models, but this would limit re-use amongst multiple clients.
Should they live with a common base class of the clients (for instance, one could imagine a "teacher" class/namespace which would also provide the non-member function makeTeacherRoom(), which would be inherited by MathTeacher and GeographyTeacher.
Should they live somewhere else completely, in a "utils" file? And if so in which namespace?

This is primarily a personal decision. Most of your options have no technical negative effects. For example:
They could, because of locality of use, but it's not necessary.
They could, because of locality of data, but again...
They could, although this one does seem like it could make things a bit messier. Making utility classes, you may have to end up inheriting them, or making parts virtual to override later, which will get ugly pretty quick.
This is my personal favorite, or a variant of this.
I typically make a relevantly-named util file (or class with static methods) and put it in the same namespace as the classes it utilates (the more helpful version of mutilate). For a Education::Teacher class, you could have a Education::TeacherUtils file or class containing the functions that operate on Teacher. This keeps a pretty obvious naming tie-in, but also puts the util functions in their own area, so they can be included from whatever needs them (in the Teacher.cpp or similar would prevent that). In the case of a class, you can make the util and base classes friends, which is occasionally helpful (but something to use rarely, as it may be a smell).
I've seen a naming variation, Education::Utils::Teacher, but that's somewhat harder to translate to files (unless you put things into a utils dir) and can also cause name resolution oddness (in some contexts, the compiler may try to use Education::Utils::Teacher instead of Education::Teacher when you didn't mean to). Because of this, I prefer to keep utils as a suffix.

You may want to handle non-member functions in a singleton class for your application. A factory maybe executed from the program, or another object.
C++ supports global functions (non member functions), but, using a single object for the application, "does the trick".
Additionally, since the "Classroom" object may be instantiated with many optional parameters, you may want to assign it, after calling the constructor ( "init" in python ).
// filename: "classrooms.cpp"
class ClassroomClass
{
protected:
int _Room_Size;
int _N_Desks;
int _N_Boards;
int _N_Books;
bool _Has_Globe;
public:
// constructor without parameters,
// but, can be declared with them
ClassroomClass()
{
_Room_Size = 0;
_N_Desks = 0;
_N_Boards = 0;
_N_Books = 0;
_Has_Globe = false;
} // ClassroomClass()
public int get_Room_Size()
{
return _Room_Size;
}
public void set_Room_Size(int Value)
{
_Room_Size = Value;
}
// other "getters" & "setters" functions
// ...
} // class ClassroomClass
class ClassroomFactoryClass
{
public:
void addRequirement(char[] AKey, char[] AValue);
} // class ClassroomFactoryClass
class MyProgramClass
{
public:
ClassroomFactoryClass Factory;
public:
void makeTeacherRoom();
void doSomething();
} // class MyProgramClass
void MyProgramClass::addRequirement(char[] AKey, char[] AValue)
{
...
} // void MyProgramClass::addRequirement(...)
void MyProgramClass::makeTeacherRoom()
{
Factory.addRequirement("n_desks", "10")
Factory.addRequirement("n_boards", "1")
} // void MyProgramClass::makeTeacherRoom(...)
void MyProgramClass::doSomething()
{
...
} // void MyProgramClass::doSomething(...)
int main(char[][] args)
{
MyProgramClass MyProgram = new MyProgramClass();
MyProgram->doSomething();
delete MyProgram();
return 0;
} // main(...)
Cheers

Personally I would make them static members of the class.
class File
{
public:
static bool load( File & file, std::string const & fileName );
private:
std::vector< char > data;
};
int main( void )
{
std::string fileName = "foo.txt";
File myFile;
File::load( myFile, fileName );
}
With static methods they have access to the private data of the class while not belonging to a specific instance of the class. It also means the methods aren't separated from the data they act on, as would be the case if you put them in a utility header somewhere.

Related

Extending Class via Multiple Private Inheritance - Is this a thing?

I'm trying to encapsulate existing functionality in a wide swathe of classes so it can be uniformly modified (e.g. mutexed, optimized, logged, etc.) For some reason, I've gotten it into my head that (multiple) private inheritance is the way to go, but I can't find what led me to that conclusion.
The question is: what is the name for what I am trying to do, and where I can see it done right?
What I think this isn't:
Decorator: All the descriptions I see for this pattern wrap a class to provide extra methods as viewed from the outside. I want to provide functionality to the inside (extract existing as well as add additional.)
Interface: This is close, because the functionality has a well-defined interface (and one I would like to mock for testing.) But again this pattern deals with the view from the outside.
I'm also open to alternatives, but the jackpot here is finding an article on it written by someone much smarter than me (a la Alexandrescu, Meyers, Sutter, etc.)
Example code:
// Original code, this stuff is all over
class SprinkledFunctionality
{
void doSomething()
{
...
int id = 42;
Db* pDb = Db::getDbInstance(); // This should be a reference or have a ptr check IRL
Thing* pThing = pDb->getAThing(id);
...
}
}
// The desired functionality has been extracted into a method, so that's good
class ExtractedFunctionality
{
void doSomething()
{
...
int id = 42;
Thing* pThing = getAThing(id);
...
}
protected:
Thing* getAThing(int id)
{
Db* pDb = Db::getDbInstance();
return pDb->getAThing(id);
}
}
// What I'm trying to do, or want to emulate
class InheritedFunctionality : private DbAccessor
{
void doSomething()
{
...
int id = 42;
Thing* pThing = getAThing(id);
...
}
}
// Now modifying this affects everyone who accesses the DB, which is even better
class DbAccessor
{
public:
Thing* getAThing(int id)
{
// Mutexing the DB access here would save a lot of effort and can't be forgotten
std::cout << "Getting thing #" << id << std::endl; // Logging is easier
Db* pDb = Db::getDbInstance(); // This can now be a ptr check in one place instead of 100+
return = pDb->getAThing(id);
}
}
One useful technique you might be overlooking is the non-virtual interface (NVI) as coined by Sutter in his writings about virtuality. It requires a slight inversion of the way you're looking at it, but is intended to address those precise concerns. It also tackles those concerns from within as opposed, to say, decorator which is about extending functionality non-intrusively from the outside.
class Foo
{
public:
void something()
{
// can add all the central code you want here for logging,
// mutex locking/unlocking, instrumentation, etc.
...
impl_something();
...
}
private:
virtual void impl_something() = 0;
};
The idea is to favor non-virtual functions for your public interfaces, but make them call virtual functions (with private or protected access) which are overridden elsewhere. This gives you both the extensibility you typically get with inheritance while retaining central control (something otherwise often lost).
Now Bar can derive from Foo and override impl_something to provide specific behavior. Yet you retain the central control in Foo to add whatever you like and affect all subclasses in the Foo hierarchy.
Initially Foo::something might not even do anything more than call Foo::impl_something, but the value here is the breathing room that provides in the future to add any central code you want -- something which can otherwise be very awkward if you're looking down at a codebase which has a boatload of dependencies directly to virtual functions. By depending on a public non-virtual function which depends on an overridden, non-public virtual function, we gain an intermediary site to which we can add all the central code we like.
Note that this can be overkill too. Everything can be overkill in SE, as a simple enough program might actually be the easiest to maintain if it just used global variables and a big main function. All of these techniques have trade-offs, but the pros begin to outweigh the cons with sufficient scale, complexity, changing requirements*.
* I noticed in one of your other questions that you wrote that the right tool for the job should have zero drawbacks, but everything tends to have drawbacks, everything is a trade-off. It's whether the pros outweigh the cons that ultimately determines whether it was a good design decision, and it's far from easy to realize all of this in foresight instead of hindsight.
As for your example:
// What I'm trying to do, or want to emulate
class InheritedFunctionality : private DbAccessor
{
void doSomething()
{
...
int id = 42;
Thing* pThing = getAThing(id);
...
}
}
... there is a significantly tighter coupling here than is necessary for this example. There might be more to it than you've shown which makes private inheritance a necessity, but otherwise composition would generally loosen the coupling considerably without much extra effort, like so:
class ComposedFunctionality
{
...
void doSomething()
{
...
int id = 42;
Thing* pThing = dbAccessor.getAThing(id);
...
}
...
private:
DbAccessor dbAccessor;
};
Basically what you're doing is decoupling the way you getAThing from the way you doSomething. Looks a lot like the Factory Method object-oriented design pattern. Have a look here:
Factory Method Pattern

Cast relatives classes to each other which has common parent class

I have classes DBGameAction and ServerGameAction which has common parent class GameAction. Classes DBGameAction and ServerGameAction it's a API for safety working with entity GameAction from different part of program.
My question is: is it normal at first create DBGameAction entity and then cast it to the ServerGameAction entity? Or maybe it's a wrong program design?
My program:
#include <vector>
#include <string>
#include <iostream>
class GameAction
{
protected:
/* Need use mutex or something else for having safety access to this entity */
unsigned int cost;
unsigned int id;
std::vector<std::string> players;
GameAction(){}
public:
unsigned int getCost() const
{
return cost;
}
};
class DBGameAction : public GameAction
{
public:
void setCost(unsigned int c)
{
cost = c;
}
void setId(unsigned int i)
{
id = i;
}
};
class ServerGameAction : public GameAction
{
ServerGameAction(){}
public:
void addPlayer(std::string p)
{
players.push_back(p);
}
std::string getLastPlayer() const
{
return players.back();
}
};
int main(int argc, char *argv[])
{
DBGameAction *dbga = 0;
ServerGameAction *sga = 0;
try {
dbga = new DBGameAction;
}
catch(...) /* Something happens wrong! */
{
return -1;
}
sga = reinterpret_cast<ServerGameAction*>(dbga);
sga->addPlayer("Max");
dbga->setCost(100);
std::cout << dbga->getCost() << std::endl;
std::cout << sga->getLastPlayer() << std::endl;
delete dbga;
sga = dbga = 0;
return 0;
}
It is wrong program design.
Is there a reason why you are not creating GameAction variables which you then downcast to DBGameAction and ServerGameAction?
I haven't used reinterpret_cast in many occasions but I am sure it shouldn't be used this way. You should try to find a better design for the interface of your classes. Someone who uses your classes, doesn't have a way to know that he needs to do this sort of castings to add a player.
You have to ask yourself, if adding a player is an operation that only makes sense for ServerGameActions or for DBGameActions too. If it makes sense to add players to DBGameActions, then AddPlayer should be in the interface of DBGameAction too. Then you will not need these casts. Taking it one step further, if it is an operation that makes sense for every possible GameAction you may ever have, you can put it in the interface of the base class.
I have used a similar pattern effectively in the past, but it is a little different than most interface class setups. Instead of having a consistent interface that can trigger appropriate class-specific methods for accomplishing similar tasks on different data types, this provides two completely different sets of functionality which each have their own interface, yet work on the same data layout.
The only reason I would pull out this design is for situations where the base class is data-only and shared between multiple libraries or executables. Then each lib or exe defines a child class which houses all the functionality that it's allowed to use on the base data. This way you can, for example, build your server executable with all kinds of nice extra functions for manipulating game data that the client isn't allowed to use, and the server-side functionality doesn't get built into the client executable. It's much easier for a game modder to trigger existing, dormant functionality than to write and inject their own.
The main part of your question about casting directly between the child classes is making us worry, though. If you find yourself wanting to do that, stop and rethink. You could theoretically get away with the cast as long as your classes stay non-virtual and the derived classes never add data members (the derived classes can't have any data for what you're trying to do anyway, due to object slicing), but it would be potentially dangerous and, most likely, less readable code. As #dspfnder was talking about, you would want to work with base classes for passing data around and down-cast on-demand to access functionality.
With all that said, there are many ways to isolate, restrict, or cull functionality. It may be worth reworking your design with functionality living in friend classes instead of child classes; that would require much less or no casting.

A better design pattern than factory?

In the code I am now creating, I have an object that can belong to two discrete types, differentiated by serial number. Something like this:
class Chips {
public:
Chips(int shelf) {m_nShelf = shelf;}
Chips(string sSerial) {m_sSerial = sSerial;}
virtual string GetFlavour() = 0;
virtual int GetShelf() {return m_nShelf;}
protected:
string m_sSerial;
int m_nShelf;
}
class Lays : Chips {
string GetFlavour()
{
if (m_sSerial[0] == '0') return "Cool ranch";
else return "";
}
}
class Pringles : Chips {
string GetFlavour()
{
if (m_sSerial.find("cool") != -1) return "Cool ranch";
else return "";
}
}
Now, the obvious choice to implement this would be using a factory design pattern. Checking manually which serial belongs to which class type wouldn't be too difficult.
However, this requires having a class that knows all the other classes and refers to them by name, which is hardly truly generic, especially if I end up having to add a whole bunch of subclasses.
To complicate things further, I may have to keep around an object for a while before I know its actual serial number, which means I may have to write the base class full of dummy functions rather than keeping it abstract and somehow replace it with an instance of one of the child classes when I do get the serial. This is also less than ideal.
Is factory design pattern truly the best way to deal with this, or does anyone have a better idea?
You can create a factory which knows only the Base class, like this:
add pure virtual method to base class: virtual Chips* clone() const=0; and implement it for all derives, just like operator= but to return pointer to a new derived. (if you have destructor, it should be virtual too)
now you can define a factory class:
Class ChipsFactory{
std::map<std::string,Chips*> m_chipsTypes;
public:
~ChipsFactory(){
//delete all pointers... I'm assuming all are dynamically allocated.
for( std::map<std::string,Chips*>::iterator it = m_chipsTypes.begin();
it!=m_chipsTypes.end(); it++) {
delete it->second;
}
}
//use this method to init every type you have
void AddChipsType(const std::string& serial, Chips* c){
m_chipsTypes[serial] = c;
}
//use this to generate object
Chips* CreateObject(const std::string& serial){
std::map<std::string,Chips*>::iterator it = m_chipsTypes.find(serial);
if(it == m_chipsTypes.end()){
return NULL;
}else{
return it->clone();
}
}
};
Initialize the factory with all types, and you can get pointers for the initialized objects types from it.
From the comments, I think you're after something like this:
class ISerialNumber
{
public:
static ISerialNumber* Create( const string& number )
{
// instantiate and return a concrete class that
// derives from ISerialNumber, or NULL
}
virtual void DoSerialNumberTypeStuff() = 0;
};
class SerialNumberedObject
{
public:
bool Initialise( const string& serialNum )
{
m_pNumber = ISerialNumber::Create( serialNum );
return m_pNumber != NULL;
}
void DoThings()
{
m_pNumber->DoSerialNumberTypeStuff();
}
private:
ISerialNumber* m_pNumber;
};
(As this was a question on more advanced concepts, protecting from null/invalid pointer issues is left as an exercise for the reader.)
Why bother with inheritance here? As far as I can see the behaviour is the same for all Chips instances. That behaviour is that the flavour is defined by the serial number.
If the serial number only changes a couple of things then you can inject or lookup the behaviours (std::function) at runtime based on the serial number using a simple map (why complicate things!). This way common behaviours are shared among different chips via their serial number mappings.
If the serial number changes a LOT of things, then I think you have the design a bit backwards. In that case what you really have is the serial number defining a configuration of the Chips, and your design should reflect that. Like this:
class SerialNumber {
public:
// Maybe use a builder along with default values
SerialNumber( .... );
// All getters, no setters.
string getFlavour() const;
private:
string flavour;
// others (package colour, price, promotion, target country etc...)
}
class Chips {
public:
// Do not own the serial number... 'tis shared.
Chips(std::shared_ptr<SerialNumber> poSerial):m_poSerial{poSerial}{}
Chips(int shelf, SerialNumber oSerial):m_poSerial{oSerial}, m_nShelf{shelf}{}
string GetFlavour() {return m_poSerial->getFlavour()};
int GetShelf() {return m_nShelf;}
protected:
std::shared_ptr<SerialNumber> m_poSerial;
int m_nShelf;
}
// stores std::shared_ptr but you could also use one of the shared containers from boost.
Chips pringles{ chipMap.at("standard pringles - sour cream") };
This way once you have a set of SerialNumbers for your products then the product behaviour does not change. The only change is the "configuration" which is encapsulated in the SerialNumber. Means that the Chips class doesn't need to change.
Anyway, somewhere someone needs to know how to build the class. Of course you could you template based injection as well but your code would need to inject the correct type.
One last idea. If SerialNumber ctor took a string (XML or JSON for example) then you could have your program read the configurations at runtime, after they have been defined by a manager type person. This would decouple the business needs from your code, and that would be a robust way to future-proof.
Oh... and I would recommend NOT using Hungarian notation. If you change the type of an object or parameter you also have to change the name. Worse you could forget to change them and other will make incorrect assumptions. Unless you are using vim/notepad to program with then the IDE will give you that info in a clearer manner.
#user1158692 - The party instantiating Chips only needs to know about SerialNumber in one of my proposed designs, and that proposed design stipulates that the SerialNumber class acts to configure the Chips class. In that case the person using Chips SHOULD know about SerialNumber because of their intimate relationship. The intimiate relationship between the classes is exactly the reason why it should be injected via constructor. Of course it is very very simple to change this to use a setter instead if necessary, but this is something I would discourage, due to the represented relationship.
I really doubt that it is absolutely necessary to create the instances of chips without knowing the serial number. I would imagine that this is an application issue rather than one that is required by the design of the class. Also, the class is not very usable without SerialNumber and if you did allow construction of the class without SerialNumber you would either need to use a default version (requiring Chips to know how to construct one of these or using a global reference!) or you would end up polluting the class with a lot of checking.
As for you complaint regarding the shared_ptr... how on earth to you propose that the ownership semantics and responsibilities are clarified? Perhaps raw pointers would be your solution but that is dangerous and unclear. The shared_ptr clearly lets designers know that they do not own the pointer and are not responsible for it.

Dealing with functions in a class that should be broken down into functions for clarity?

How is this situation usually dealt with. For example, an object may need to do very specific things:
class Human
{
public:
void eat(Food food);
void drink(Liquid liquid);
String talkTo(Human human);
}
Say that this is what this class is supposed to do, but to actually do these might result in functions that are well over 10,000 lines. So you would break them down. The problem is, many of those helper functions should not be called by anything other than the function they are serving. This makes the code confusing in a way. For example, chew(Food food); would be called by eat() but should not be called by a user of the class and probably should not be called anywhere else.
How are these cases dealt with generally. I was looking at some classes from a real video game that looked like this:
class CHeli (7 variables, 19 functions)
Variables list
CatalinaHasBeenShotDown
CatalinaHeliOn
NumScriptHelis
NumRandomHelis
TestForNewRandomHelisTimer
ScriptHeliOn
pHelis
Functions list
FindPointerToCatalinasHeli (void)
GenerateHeli (b)
CatalinaTakeOff (void)
ActivateHeli (b)
MakeCatalinaHeliFlyAway (void)
HasCatalinaBeenShotDown (void)
InitHelis (void)
UpdateHelis (void)
TestRocketCollision (P7CVector)
TestBulletCollision (P7CVectorP7CVectorP7CVector)
SpecialHeliPreRender (void)
SpawnFlyingComponent (i)
StartCatalinaFlyBy (void)
RemoveCatalinaHeli (void)
Render (void)
SetModelIndex (Ui)
PreRenderAlways (void)
ProcessControl (void)
PreRender (void)
All of these look like fairly high level functions, which mean their source code must be pretty lengthy. What is good about this is that at a glance it is very clear what this class can do and the class looks easy to use. However, the code for these functions might be quite large.
What should a programmer do in these cases; what is proper practice for these types of situations.
For example, chew(Food food); would be called by eat() but should not be called by a user of the class and probably should not be called anywhere else.
Then either make chew a private or protected member function, or a freestanding function in an anonymous namespace inside the eat implementation module:
// eat.cc
// details of digestion
namespace {
void chew(Human &subject, Food &food)
{
while (!food.mushy())
subject.move_jaws();
}
}
void Human::eat(Food &food)
{
chew(*this, food);
swallow(*this, food);
}
The benefits of this approach compared to private member functions is that the implementation of eat can be changed without the header changing (requiring recompilation of client code). The drawback is that the function cannot be called by any function outside of its module, so it can't be shared by multiple member functions unless they share an implementation file, and that it can't access private parts of the class directly.
The drawback compared to protected member functions is that derived classes can't call chew directly.
The implementation of one member function is allowed to be split in whatever way you want.
A popular option is to use private member functions:
struct Human
{
void eat();
private:
void chew(...);
void eat_spinach();
...
};
or to use the Pimpl idiom:
struct Human
{
void eat();
private:
struct impl;
std::unique_ptr<impl> p_impl;
};
struct Human::impl { ... };
However, as soon as the complexity of eat goes up, you surely don't want a collection of private methods accumulating (be it inside a Pimpl class or inside a private section).
So you want to break down the behavior. You can use classes:
struct SpinachEater
{
void eat_spinach();
private:
// Helpers for eating spinach
};
...
void Human::eat(Aliment* e)
{
if (e->isSpinach()) // Use your favorite dispatch method here
// Factories, or some sort of polymorphism
// are possible ideas.
{
SpinachEater eater;
eater.eat_spinach();
}
...
}
with the basic principles:
Keep it simple
One class one responsibility
Never duplicate code
Edit: A slightly better illustration, showing a possible split into classes:
struct Aliment;
struct Human
{
void eat(Aliment* e);
private:
void process(Aliment* e);
void chew();
void swallow();
void throw_up();
};
// Everything below is in an implementation file
// As the code grows, it can of course be split into several
// implementation files.
struct AlimentProcessor
{
virtual ~AlimentProcessor() {}
virtual process() {}
};
struct VegetableProcessor : AlimentProcessor
{
private:
virtual process() { std::cout << "Eeek\n"; }
};
struct MeatProcessor
{
private:
virtual process() { std::cout << "Hmmm\n"; }
};
// Use your favorite dispatch method here.
// There are many ways to escape the use of dynamic_cast,
// especially if the number of aliments is expected to grow.
std::unique_ptr<AlimentProcessor> Factory(Aliment* e)
{
typedef std::unique_ptr<AlimentProcessor> Handle;
if (dynamic_cast<Vegetable*>(e))
return Handle(new VegetableProcessor);
else if (dynamic_cast<Meat*>(e))
return Handle(new MeatProcessor);
else
return Handle(new AlimentProcessor);
};
void Human::eat(Aliment* e)
{
this->process(e);
this->chew();
if (e->isGood()) this->swallow();
else this->throw_up();
}
void Human::process(Aliment* e)
{
Factory(e)->process();
}
One possibility is to (perhaps privately) compose the Human of smaller objects that each do a smaller part of the work. So, you might have a Stomach object. Human::eat(Food food) would delegate to this->stomach.digest(food), returning a DigestedFood object, which the Human::eat(Food food) function processed further.
Function decomposition is something that is learnt from experience, and it usually implies type decomposition at the same time. If your functions become too large there are different things that can be done, which is best for a particular case depends on the problem at hand.
separate functionality into private functions
This makes more sense when the functions have to access quite a bit of state from the object, and if they can be used as building blocks for one or more of the public functions
decompose the class into different subclasses that have different responsibilities
In some cases a part of the work falls naturally into its own little subproblem, then the higher level functions can be implemented in terms of calls to the internal subobjects (usually members of the type).
Because the domain that you are trying to model can be interpreted in quite a number of different ways I fear trying to provide a sensible breakdown, but you could imagine that you had a mouth subobject in Human that you could use to ingest food or drink. Inside the mouth subobject you could have functions open, chew, swallow...

Efficient way to generate id unique to class?

Is there any efficient way in C++ of generating an ID unique to the class, not to the instance? I'm looking for something of this level of simplicity (this generates an ID for every instance, not for every class type):
MyClass::MyClass()
{
static unsigned int i = 0;
id_ = i++;
}
Edit: Why I want unique IDs.
I'm writing a game. All entities in my game will have different states they can be in (walking left, jumping, standing, etc); these states are defined in classes. Each state needs to have its own ID so I can identify it.
You can try this, but it's not-deterministic.
int id_count = 0;
template <typename T>
int get_id()
{
static int id = id_count++;
return id;
}
Then just use:
get_id<int>(); // etc.
Of course, this isn't thread safe.
Again, it's not deterministic: the IDs are generated the first time you call the function for each type. So, if on one run you call get_id<int>() before get_id<float>() then on another run you call them the other way round then they'll have different IDs. However, they will always be unique for each type in a single run.
Basically you are asking for a custom rolled RTTI solution, that you can selectively apply to classes.
This can start from very crude preprocessor stuff like :
#define DECLARE_RTTI_CLASS(a) class a { \
inline const char * class_id() { return #a };
.. to a more sophisticated solutions that track inheritance etc, essentially partially duplicating compiler RTTI functionality. For an example, see Game Programming Gems #2, Dynamic Type Information
Previous discussions on gamedev on the same subject are also worth reading
Use your MyClass as a primitive, and incorporate a static instance of one into each class you want to ID.
class MyOtherClass1 {
static MyClass id;
};
class MyOtherClass2 {
static MyClass id;
};
[etc.]