title: C++ - Accessing multiple object's interfaces via a single pointer
body: <p>I need to store a container of pointers to objects.
  These objects have some common methods/attributes (interface) that I want to enforce (possibly at compile time) and use.
  Example:</p>
  
  <pre><code>struct A{
      void fly(){}
  };
  
  struct B{
      void fly(){}
  };
  
  A a;
  B b;
  std::vector&lt;some *&gt; objects;
  objects.push_back(&amp;a);
  objects.push_back(&amp;b);
  
  for(auto &amp; el: objects)
      el-&gt;fly();
  </code></pre>
  
  <p>The simpler solution would be <code>A</code> and <code>B</code> inherit a common base class like <code>FlyingClass</code>:</p>
  
  <pre><code>struct FlyingClass{
      void fly(){}
  };
  struct A: public FlyingClass { ...
  struct B: public FlyingClass { ...
  </code></pre>
  
  <p>and create a</p>
  
  <pre><code>std::vector&lt;FlyingClass *&gt; objects;
  </code></pre>
  
  <p>This will work and also enforce the fact that I can only add to <code>objects</code> things that can fly (implement <code>FlyingClass</code>).</p>
  
  <p>But what if I need to implement some other common methods/attributes WITHOUT coupling them with the above base class?</p>
  
  <p>Example:</p>
  
  <pre><code>struct A{
      void fly(){}
      void swim(){}
  };
  
  struct B{
      void fly(){}
      void swim(){}
  };
  </code></pre>
  
  <p>And i would like to do:</p>
  
  <pre><code>for(auto &amp; el: objects) {
      el-&gt;fly();
      ...
      el-&gt;swim();
      ...
  }
  </code></pre>
  
  <p>More in general i would be able to call a function passing one of these pointers and access both the common methods/attributes, like:</p>
  
  <pre><code>void dostuff(Element * el){
      el-&gt;fly();
      el-&gt;swim();
  }
  </code></pre>
  
  <p>I could try to inherit from another interface like:</p>
  
  <pre><code>struct SwimmingClass{
      void swim(){}
  };
  
  struct A: public FlyingClass, public SwimmingClass { ...
  struct B: public FlyingClass, public SwimmingClass { ...
  </code></pre>
  
  <p>But then what the container should contain?</p>
  
  <pre><code>std::vector&lt;FlyingClass&amp;&amp;SwimmingClass *&gt; objects;
  </code></pre>
  
  <p>Sure, i could implement <code>SwimmingFlyingClass</code>, but what if i need <code>RunningClass</code> etc.. This is going to be a nightmare.
  In other words, how can I implement a pointer to multiple interfaces without coupling them?</p>
  
  <p>Or there is some template way of rethinking the problem?
  Even run time type information could be acceptable in my application, if there is an elegant and maintainable way of doing this.</p>