dead_OTMOPO3
dead_OTMOPO3

Reputation: 83

Overriding virtual method in c++

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:

#include <iostream>  

using namespace std;  

class B;  

class A  {  
  public:  
    A(B& b_) : b(b_) {};

    B& b;  

    virtual void printon() {
        cout << "Test virtual printon A\n" << endl;
    }
    void print() {
        cout << "Test print A\n";
        printon();
    }  
};   

class B  {  
  protected:  
    A a;  
  public:  
    B() : a(*this) {};

    void print() {
        a.print();
    };  
};  

And in my program I can use it like:

int main()   {  
    B* b = new B();  
    b->print();  
    return 0;  
}  

Actually method a.printon() 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".

I can create a derived class newA:

class newA : public A {  
  public:  
    newA(B& b_) : A(b_) {};

    virtual void printon() {
        cout << "Test printon newA"<< endl;
    }
};  

And I'm not sure, what to do next. Maybe create a class newB, like:

class newB : public B {
  public:
    newB() : B() {};  
};  

But how to make B.a of type A act like type newA?

Upvotes: 0

Views: 122

Answers (1)

Mark B
Mark B

Reputation: 96311

B contains A by value, which precludes the use of polymorphism (if you tried to set a newA into the A object, you get object slicing. If you want your B to be able to use derived versions of A you'd need to store it by (smart) pointer.

Upvotes: 2

Related Questions