C ++ constructor overload resolution with multiple inheritance

I have a short snippet of code that I would like to get a little more information about why overload resolution selects one constructor over another. Here is the code in question:

#include <iostream> struct Base { }; struct Other { Other(const Other&) { std::cout << "Copy Constructor\n"; } Other(const Base&) { std::cout << "Custom Constructor\n"; } }; struct Derived : public Base, public Other { Derived() : Other(*this) { } }; int main() { Derived derived; // Prints "Copy Constructor" system("pause"); return 0; } 

I assume there is a section in the C ++ standard that defines the copy constructor as a better match than user-defined constructors *? My assumption otherwise was that if there were no rule favorable to the copy constructor, then the compiler would either in order of inheritance (as with the construction order with multiple inheritance) or simply give me an ambiguous error in calling the constructor. However, changing the order in which Derived inherits from Base and Other does not change the result, which makes me think that my initial assumption of preferred copy constructors is correct. Can someone point me to a rule defining the behavior that I see?

* I checked cppreference.com The Overload Resolution page , but I didn’t see a single rule there that explained the behavior I’m seeing (although I am not completely fluent in the standard, so I could easily skip it).

+5
source share
1 answer

The reason the code snippet is compiled due to the non-standard behavior of Visual Studio (I currently use VS2017.3 Preview, which compiles the code without errors even with / permissive -flag). The following is the error coming from GCC and Clang:

NCA

 Error(s): source_file.cpp: In constructor 'Derived::Derived()': source_file.cpp:25:20: error: call of overloaded 'Other(Derived&)' is ambiguous Other(*this) ^ source_file.cpp:16:5: note: candidate: Other::Other(const Base&) Other(const Base&) ^ source_file.cpp:12:5: note: candidate: Other::Other(const Other&) Other(const Other&) ^ 

Clang

 Error(s): source_file.cpp:25:9: error: call to constructor of 'Other' is ambiguous Other(*this) ^ ~~~~~ source_file.cpp:12:5: note: candidate constructor Other(const Other&) ^ source_file.cpp:16:5: note: candidate constructor Other(const Base&) ^ 1 error generated. 

Error output from http://rextester.com/ .

+1
source

Source: https://habr.com/ru/post/1270175/


All Articles