Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Scoping and ambiguity in constructor overloads

Tags:

c++

I've tried the following code snippet in 3 different compilers (G++, clang++, CL.exe) and they all report to me that they cannot disambiguate the overloaded constructors. Now, I know how I could modify the call to the constructor to make it pick one or the other (either make explicit that the second argument is a unsigned literal value or explicitly cast it).

However, I'm curious why the compiler would be attempting to choose between constructors in the first place given that one of the constructors is private and the call to the constructor is happening in the main function which should be outside the class's scope.

Can anyone 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
}
like image 452
Larry Olson Avatar asked Jan 23 '23 00:01

Larry Olson


1 Answers

In C++, accessibility to class members doesn't influence the other language semantics. Instead, any invalid access causes a program to be ill-formed.

In other words, there is accessibility and visibility. The Standard has it straight

It should be noted that it is access to members and base classes that is controlled, not their visibility. Names of members are still visible, and implicit conversions to base classes are still considered, when those members and base classes are inaccessible. The interpretation of a given construct is established without regard to access control. If the interpretation established makes use of inaccessible member names or base classes, the construct is ill-formed.

like image 127
Johannes Schaub - litb Avatar answered Jan 30 '23 07:01

Johannes Schaub - litb