Question

Ok so I have a question relating to the output of the following code (which is 111222223)

#include <iostream>
struct C {
 virtual int eq(const C& other) const { return 1; }
};
struct SC : C {
 virtual int eq(const C& other) const { return 2; } 
 virtual int eq(const SC& other) const { return 3; }
};
void go(const C& c, const C& c1, const SC& sc) {
 using namespace std;

 cout << c.eq(c) << endl;
 cout << c.eq(c1) << endl;
 cout << c.eq(sc) << endl;

 cout << c1.eq(c) << endl;
 cout << c1.eq(c1) << endl;
 cout << c1.eq(sc) << endl;

 cout << sc.eq(c) << endl;
 cout << sc.eq(c1) << endl;
 cout << sc.eq(sc) << endl;
}
int main(int argc, const char* argv[]) { 
 go(C(), SC(), SC());
 return 0;
}

So I understand that I am using the dot operator with a reference that will dynamically bind the proper virtual method based on the run-time type of the caller (would need -> with pointers but OK for dynamic minding here). What I don't understand is why the second to last cout line prints '2' and not '3'. Is this because the method signature is static, so the method is selected based on the static signature in the proper derived type SC? Thanks for the help in advance!

Was it helpful?

Solution

In C++ there is no support for multiple dispatch, only for the object on which the function is called (dynamic dispatch only applies to the this pointer). In the expression:

sc.eq(c1);

the compiler will dispatch to the dynamic type of sc, but will use the static type of c1

OTHER TIPS

This is due to function resolution rules.

In this call:

sc.eq(c1);

Only one function is elegible to be called, once c1 is of type struct C with eq dynamicly overloaded.

But in the call

sc.eq(sc);

you have two possible eq functions to be called. The first one is declared in struct C with the dynamicly overloaded eq and the second is the one declared in struct SC. Once sc is of type struct SC the last method is more viable than the former.

That why you are getting 3 as result.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top