title: "Define" a member function in class constructor
body: <p>Hello all together,</p>
  
  <p>I'm wondering if you are able to define or instantiate a function for example in the constructor of a class.</p>
  
  <p>Let's say you have this simple class:</p>
  
  <pre><code>class cTest {
  public:
      cTest( bool bla );
      ~cTest() {}
  
      void someFunc() {}
  };
  
  cTest::cTest( bool bla ) {
      if( bla ) {
          someFunc = functionBody1;
          // or
          someFunc {
              functionBody1
          };
          // or something different
      } else
          someFunc = functionBody2;
  }
  </code></pre>
  
  <p>if someFunc is an often called function, you could avoid testing whether "bla" was true or not every time the function gets called.</p>
  
  <p>I thought about it and two possible solutions came to my mind:</p>
  
  <p><strong>1) Using inheritance:</strong></p>
  
  <pre><code>#include &lt;iostream&gt;
  
  class iTest {
  public:
      virtual void someFunc() = 0;
  };
  
  class cTest1 : public iTest {
  public:
      void someFunc() { std::cout &lt;&lt; "functionBody1\n"; }
  };
  
  class cTest2 : public iTest {
  public:
      void someFunc() { std::cout &lt;&lt; "functionBody2\n"; }
  };
  </code></pre>
  
  <p><strong>2) Using function pointers:</strong></p>
  
  <pre><code>#include &lt;iostream&gt;
  
  class cTest {
  public:
      cTest( bool bla );
      ~cTest() {}
  
      void someFunc();
  private:
      void ( cTest::*m_functionPointer )();
  
      void function1() { std::cout &lt;&lt; "functionBody1\n"; }
      void function2() { std::cout &lt;&lt; "functionBody2\n"; }
  };
  
  cTest::cTest( bool bla ) {
      if( bla )
          m_functionPointer = &amp;cTest::function1;
      else
          m_functionPointer = &amp;cTest::function2;
  };
  
  void cTest::someFunc() {
      ( *this.*m_functionPointer )( );
  };
  </code></pre>
  
  <p>In the program where I need this I cannot use inheritance and don't want to use function pointers.
  So my question is, is there another (elegant) way to do this, e.g. defining the function in the constructor of the class?</p>
  
  <p>Thanks a lot for your answers!</p>