title: C++ Components based class
body: <p><p>Hi,
  <p>I'm writing a component based class with a container, but after thinking of many different approaches, I can't find one that follows really what I want.
  <p>Here is an example of the general idea :</p>
  
  <p><img src="https://i.stack.imgur.com/2qm4M.jpg" alt="http://imageshack.us/photo/my-images/713/38394964.png/"></p>
  
  <p><br>
  And the code I already wrote :
  <br>
  <br></p>
  
  <pre><code>// Abstract class Component
  class Component
  {
  public :
      virtual ~Component() = 0;
      virtual int GetResult() = 0;
  };
  
  
  class AddComponent : Component
  {
  public :
      int GetResult() { return input1-&gt;GetResult() + input2-&gt;GetResult(); }
  
      void SetInput1(Component* c) { input1 = c; }
      void SetInput2(Component* c) { input2 = c; }
  
  private :
      Component* input1;
      Component* input2;
  };
  
  class ConstComponent : Component
  {
  public :
      int GetResult() { return value; }
  
      void SetValue(int x) { value = x; }
  
  private :
      int value;
  };
  
  class SignComponent : Component
  {
  public :
      int GetResult() { return sign(input-&gt;GetResult()); }
  
      void SetInput(Component* c) { input = c; }
  
  private :
      Component* input;
  };
  
  
  class Container
  {
  public :
      Container();
      ~Container();
  
      void SetRootComponent(Component* c) { rootComponent = c; }
  
      int GetResult() { return rootComponent-&gt;GetResult(); }
  
      AddComponent* AddComponentAdd();
      ConstComponent* ConstComponentAdd();
      SignComponent* SignComponentAdd();
  
  private :
      Component* rootComponent;
      std::vector&lt;Component*&gt; components;
  };
  
  
  void main(void)
  {
      // Create container
      Container container = Container();
  
      // Create components
      SignComponent*    cSign = container.AddComponentSign();
      AddComponent*      cAdd = container.AddComponentAdd();
      ConstComponent* cConst1 = container.AddComponentConst();
      ConstComponent* cConst2 = container.AddComponentConst();
  
      // Link components
      cSign-&gt;SetInput(cAdd);
      cAdd-&gt;SetInput1(cConst1);
      cAdd-&gt;SetInput2(cConst2);
      cConst1-&gt;SetValue(-5);
      cConst2-&gt;SetValue(3);
  
      // Set root component for container
      container.SetRootComponent(cSign);
  
      // Compute
      int result = container.GetResult();
  }
  </code></pre>
  
  <p><br>
  <br>
  <p>This doesn't even compile, because of the cast of "XComponent" to "Component", which is abstract. I'm pretty sure there is a much better (and simpler ?) way to do it anyway, but I'm out of ideas.</p>