title: C++ How to call common method from classes without a shared superclass?
body: <p>The following code gives a cross/jump label initialization compile errors, of course.  But how do I get the effect I'm trying to achieve?  That is, only instantiating the class I really need, and then generically calling the method which is common to all classes?</p>
  
  <p>Class A and class B are actually not in my code, but in a large library I'm using, so can't be changed to help.  They are NOT children of a superclass (which would solve the problem).  </p>
  
  <p>Both real classes handle similar data, so are compatible in the way illustrated below with the filter() method.  I know a number of ugly C hacks which might be used to make it work, but I am looking for C++ idiomatic solutions.</p>
  
  <p>In the real problem, there is a lot more code and many more cases, and the constructor and class methods are resource intensive, so I can't just init all possible classes "just in case" and then pick the right filter() method with the switch ().</p>
  
  <pre><code>#include &lt;string&gt;
  #include &lt;iostream&gt;
  class A {
  public:
      std::string msg;
      A(std::string s) { msg = s;}
      void filter() { std::cout &lt;&lt; "Message A = " &lt;&lt; msg &lt;&lt; std::endl;}
  };
  
  class B {
  public:
      std::string msg;
      B(std::string s) { msg = s;}
      void filter() { std::cout &lt;&lt; "The B message: " &lt;&lt; msg &lt;&lt; std::endl;}
  };
  
  int main() {
      int type = 1;
      switch (type) {
      case 1:
          A f("hi from A");
          break;
      case 2:
          B f("hello from B");
          break;
      }
      f.filter();
  }
  </code></pre>
  
  <p>EDIT:  Based on @stefan's answer, I revised my code to look like what's below.  I haven't tried it in the real situation yet, but I believe it will work.  (Thanks all!)</p>
  
  <pre><code>#include &lt;string&gt;
  #include &lt;iostream&gt;
  class A {
  public:
      std::string msg;
      A(std::string s) { msg = s;}
      void filter() { std::cout &lt;&lt; "Message A = " &lt;&lt; msg &lt;&lt; std::endl;}
  };
  
  class B {
  public:
      std::string msg;
      B(std::string s) { msg = s;}
      void filter() { std::cout &lt;&lt; "The B message: " &lt;&lt; msg &lt;&lt; std::endl;}
  };
  
  template &lt;class F&gt;
  void doFilterStuff(std::string msg) {
      F f(msg);
      f.filter();
  }
  
  int main() {
      for (int i=1; i&lt;4; i++) {
          std::cout &lt;&lt; "Type = " &lt;&lt; i &lt;&lt; std::endl;
          switch (i) {
          case 1:
              doFilterStuff&lt;A&gt;("hi from A");
              break;
          case 2:
              doFilterStuff&lt;B&gt;("hello from B");
              break;
          default:
              std::cout &lt;&lt; "Throwing an error exception" &lt;&lt; std::endl;
          }
      }
  }
  </code></pre>