title: C++ - multiple inheritance for dynamic casting
body: <p>I have two classes <code>Foo</code> and <code>Bar</code>. I have a data loader that loads data from file and return them as <code>Foo</code> or <code>Bar</code>.</p>
  
  <p>Currently I have the solution as: </p>
  
  <pre><code>struct Foo { 
    std::vector&lt;Foo&gt; Filter() {
       //do something with data and return new Foo's
    }
    std::vector&lt;int&gt; data; 
  }
  
  struct Bar : protected Foo {
    std::vector&lt;Bar&gt; Filter() {
       //do something with data and return new Bar's
    }
  }
  
  template &lt;typename T&gt;
  DataLoader&lt;T&gt; { 
      .... 
      T &amp; Get() { ... }
  }
  </code></pre>
  
  <p>where <code>T</code> is either <code>Foo</code> or <code>Bar</code>.</p>
  
  <p>The problem with this solution is that I cannot dynamically choose to return <code>Foo</code> or <code>Bar</code>. I have to reload data. Ue of virtual method is not working, since <code>Filter</code> has different return types. Also, making inheritance public is not an option, because in that case I could do <code>Foo f = Bar();</code> which I dont want to enable.</p>
  
  <p>I have come up with a solution using multiple inheritance. However, I am not sure if it is correct or it would produce undefined-behaviour.</p>
  
  <p>I have added private class to <code>DataLoader</code>:</p>
  
  <pre><code>struct FooBarStorage : virtual public Foo, public Bar {}
  </code></pre>
  
  <p>and changed inheritance in <code>Bar</code> to <code>struct Bar : virtual protected Foo</code>.</p>
  
  <p>Now I can have non-templated <code>DataLoader</code>:</p>
  
  <pre><code>class DataLoader {
  
    template &lt;typename T&gt; T &amp; Get() { ... }
  }
  </code></pre>
  
  <p>and specialise <code>Get</code> to return <code>Bar &amp;</code> or <code>Foo &amp;</code>. The advantage is, I can load data only once and decide what to return in runtime. With a previous solution, data were loaded with a given type (<code>Foo</code> or <code>Bar</code>) and I was not able to change the type. </p>
  
  <p>Is this a possible working solution or would it produce undefined-behaviour / other problems / performance impacts?</p>