Issue with C++ dispatch to base

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)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#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;
}
This compiles:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#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) {
		*reinterpret_cast<Base*>(this) << something;
	}

	 void operator<<(SomethingUnrelated somethingUnrelated) { }
};

int main(int argc, const char* argv[]) {
	Something something;
	Derived derived;
	derived.work(something);
	return 0;
}

Topic archived. No new replies allowed.