This example is based upon "Subobject Members", Stephen Dewhurst,
C++ Report, V5 N3. This is part 3 of a multipart example.
In this example, we assume the engine with two buttons as before.
Rather than using inheritance to handle the relationships between
the buttons and the engine, we will use "has-a". The buttons will
have knowledge of the engine that they are embedded within.
.................................................................
class Engine {
// ...
public:
Engine ();
void start ();
void stop ();
private:
class EngineButton : public Button {
Engine &e;
void (Engine::*f) ();
EngineButton (Engine& er, void (Engine::*fp)())
: e(er), f(fp) {}
void press () { (e.*f) (); }
friend Engine;
};
EngineButton start_b;
EngineButton stop_b;
};
Engine :: Engine () : start_b(*this, start), stop_b(*this, stop) {}
.................................................................
This solution does not pollute the global namespace since EngineButton
is defined within the Engine class. Also the Engine class knows
exactly how many buttons it has (and can initialize them properly).