News:

This week IPhone 15 Pro winner is karn
You can be too a winner! Become the top poster of the week and win valuable prizes.  More details are You are not allowed to view links. Register or Login 

Main Menu

C++ tips - Callbacks and multiple inheritance, part III

Started by ben2ong2, October 07, 2006, 04:02:20 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

ben2ong2

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).
You are not allowed to view links. Register or Login
You are not allowed to view links. Register or Login