how to avoid poilymophic call in base class

Viewed 47

I have a class in which some methods call other methods like in the following example:

class Base {
public:
    virtual void foo() {
        cout << "base::foo" << endl;
        bar();
    }
    virtual void bar() {
        cout << "base::bar" << endl;
    }
};

Then I want to make a wrapper class in which each method calls the base class method and some additional stuff that I use for some tests.

class Derived :public Base {
public:
    void foo() override {
        cout << "derived::foo" << endl;
        Base::foo();
    } 
    void bar() override {
        cout << "derived::bar" << endl;
        Base::bar();
    }
};

My program was calling functions from Base class and I've changed it to call from Derived class.

int main() {
    //Base A;
    Derived A;
    A.foo();
    return 0;
}

In the above example when I call Derived::foo(), it calls Base::foo(), which in turn calls bar(); Due to polymorphism, when bar() is called from Base::foo(), it is resolved to Derived::bar(). I would like that Base::foo() to call Base::bar() and only the calls from Derived to call Base methods. Is it possible to achieve this without modifying the base class?

1 Answers

You can use static dispatch to a virtual function by qualifying the name of the function:

virtual void foo() {
    cout << "base::foo" << endl;
    Base::bar();
}

Is it possible to achieve this without modifying the base class?

I don't think so; at least not if you count modifying the definition of the member functions of the base class.

Related