title: Overriding virtual method in c++
body: <p>I've got a library with a lot of classes. And I want to modify behaviour of one virtual method of some class. I tried to simplify, what I've got, and here it is:   </p>
  
  <pre><code>#include &lt;iostream&gt;  
  
  using namespace std;  
  
  class B;  
  
  class A  {  
    public:  
      A(B&amp; b_) : b(b_) {};
  
      B&amp; b;  
  
      virtual void printon() {
          cout &lt;&lt; "Test virtual printon A\n" &lt;&lt; endl;
      }
      void print() {
          cout &lt;&lt; "Test print A\n";
          printon();
      }  
  };   
  
  class B  {  
    protected:  
      A a;  
    public:  
      B() : a(*this) {};
  
      void print() {
          a.print();
      };  
  };  
  </code></pre>
  
  <p>And in my program I can use it like:  </p>
  
  <pre><code>int main()   {  
      B* b = new B();  
      b-&gt;print();  
      return 0;  
  }  
  </code></pre>
  
  <p>Actually method <code>a.printon()</code> is called from some other code and different conditions and doesn't print anything (it does some other actions). And I need to override this method to do something else, eg print "test2".  </p>
  
  <p>I can create a derived class <code>newA</code>:</p>
  
  <pre><code>class newA : public A {  
    public:  
      newA(B&amp; b_) : A(b_) {};
  
      virtual void printon() {
          cout &lt;&lt; "Test printon newA"&lt;&lt; endl;
      }
  };  
  </code></pre>
  
  <p>And I'm not sure, what to do next. Maybe create a class <code>newB</code>, like:  </p>
  
  <pre><code>class newB : public B {
    public:
      newB() : B() {};  
  };  
  </code></pre>
  
  <p>But how to make <code>B.a</code> of type <code>A</code> act like type <code>newA</code>?</p>