psb
psb

Reputation: 402

Call hidden (non virtual) method of derived class from base

Is there a way (templates, macros anything else) to substitute a call to hidden_in_derived from common method at compile time, so that instance of Derived calls it's own hidden_in_derived (without making hidden_in_derived virtual in Base) ?

#include <iostream>

class Base {
public:
    void common() {
        // some calls to other methods
        hidden_in_derived();
        // yet some calls to other methods
    }

    void hidden_in_derived() {
        std::cout << "A" << std::endl;
    }
};

class Derived : public Base {
public:
    void hidden_in_derived() {
        std::cout << "B" << std::endl;
    }
};


int main() {
    Derived d;
    d.common(); // want hidden_in_derived (prints "B") here somehow ?

}

Upvotes: 1

Views: 302

Answers (1)

bialy
bialy

Reputation: 192

Make it virtual, then you can even use Base class ptr: https://wandbox.org/permlink/tF5Cb4fE5jEhG5Ru

Or just like you did with an object: https://wandbox.org/permlink/W2EJGXwioXjqd1Zx

Upvotes: 0

Related Questions