1

Please forgive me if I fundamentally misunderstand something about dispatch in C++!

The code as pasted below works as intended.

However, if I uncomment/add the additional operator<< method in Derived (which should handle a different agrument type), C++ is then unable to resolve the previously-working dispatch "*this << something" (which, in the absence of that method, is successfully dispatched to Base as intended).

It says:

main.cpp:25:15: Invalid operands to binary expression ('Derived' and 'Something')

Please could someone explain to me why this happens?

Thanks in advance

(Mac OS Monterey 12.2.1, xCode 13.2.1)

#include <iostream>

class Something { };
class SomethingUnrelated { };

class Base {
public:
    virtual void method() = 0;
    void operator<<(Something something) {
        method();
    }
};

class Derived : public Base {
public:
    void method() { std::cout << "Derived::method() - Yay!" << std::endl; }
    void work(Something something) {
        *this << something;
    }
    // void operator<<(SomethingUnrelated somethingUnrelated) { }
};

int main(int argc, const char * argv[]) {
    Something something;
    Derived derived;
    derived.work(something);
    return 0;
}
ttpjd1
  • 13
  • 4
  • Your function in the derived hides the base function. See: [What are the differences between overriding virtual functions and hiding non-virtual functions?](https://stackoverflow.com/questions/19736281/what-are-the-differences-between-overriding-virtual-functions-and-hiding-non-vir) – Amir Kirsh Feb 12 '22 at 18:27

1 Answers1

1

The names in the parent class are hidden while building a lookup set for the unqualified name lookup. You may bring the parent's operator to a child lookup set by using directive. I can't find the duplicated question, but I'm pretty sure the duplicated question exists.

class Derived : public Base {
public:
    void method() { std::cout << "Derived::method() - Yay!" << std::endl; }
    void work(Something something) {
        *this << something;
    }
    using Base::operator<<;
    void operator<<(SomethingUnrelated somethingUnrelated) { }
};
273K
  • 29,503
  • 10
  • 41
  • 64
  • Thank you very much. I've learned something new! (Sorry for the delayed response - been out of action with COVID since I posted). – ttpjd1 Feb 21 '22 at 13:57