Tim
Tim

Reputation: 5691

Calling function from derived scope

I have some code which seems similair to this:

#include <iostream>

class Base {
public:
    void test() {
        std::cout << "Base::test()" << std::endl; 
    }

    void test2() {
        test();
    }
};

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

int main() {
    Derived d;
    d.test2();
    return 0;
}

Now this outputs ofcourse Base::test(), however I want it to output Derived::test() without making use of virtual function calls and using an different notation for the function overload called: Derived::test.

Does someone know if this is possible to achieve?

Upvotes: 0

Views: 110

Answers (1)

Andy Prowl
Andy Prowl

Reputation: 126552

You could use the so-called Curiously Recurring Type Pattern (CRTP) and make Base a class template:

template<typename D>
class Base {
public:
    void test() {
        std::cout << "Base::test()" << std::endl;
    }

    void test2() {
        (static_cast<D*>(this))->test();
    }
};

Then, you would derive Derived from Base<Derived> instead of just Base:

class Derived : public Base<Derived> {
//                     ^^^^^^^^^^^^^
//                     This is the only change required in Derived
public:
    void test() {
        std::cout << "Derived::test()" << std::endl;
    }
};

Here is a live example.

Upvotes: 3

Related Questions