C ++ Scope and Uncertainty in Constructor Overloads

I tried the following code snippet in three different compilers (g ++, clang ++, CL.exe), and they all tell me that they cannot eliminate the ambiguous overloaded constructors. Now I know how I can change the constructor call so that it chooses one or the other (either make it explicit that the second argument is an unsigned value, or explicitly it).

However, I am curious why the compiler will try to choose between the constructors in the first place, given that one of the constructors is private, and the constructor is called in the main function, which should be outside the scope of the class,

Can someone enlighten me?

class Test { private: Test(unsigned int a, unsigned int *b) { } public: Test(unsigned int a, unsigned int b) { } }; int main() { Test t1 = Test(1,0); // compiler is confused } 
+4
source share
4 answers

In C ++, access to class members does not affect the semantics of another language. Instead, any invalid access causes the program to malfunction.

In other words, there is accessibility and visibility . Standard has direct

It should be noted that this is access to elements and base classes that are controlled, and not to their visibility. Member names are still visible, and implicit conversions to base classes are still considered when these members and base classes are not available. The interpretation of this design is established without regard to access control. If the established interpretation uses invalid member names or base classes, the construct is poorly formed.

+6
source

The compiler does not try to select an overloaded function or constructor by its visibility.

+1
source

Moreover, the compiler will not abandon the candidate function, even if it is marked as private. This means that changing the visibility of an element will not change the existing code.

+1
source

As for your second question, permission to overload occurs before the visibility check.

As for the first, you need to tell the compiler that 0 is an unsigned int. As for the compiler, converting from integer 0 to unsigned int is no better than converting from integer 0 to pointer.

+1
source

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


All Articles