4

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
}

4 Answers 4

6

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.

1
  • Wow. Thank you. I read over this very section of the spec last night and somehow missed this tidbit but thats got it. May 23, 2010 at 17:16
1

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

1

It is more that the compiler will not refuse a candidate function even if it is marked as private. This means changing visability of a member will not changing existing code.

1

As for your second question, overload resolution happens before the test for visibility.

As for the first, you need to indicate to the compiler that the 0 is an unsigned int. As far as the compiler is concerned, the conversion from integer 0 to unsigned int is no better than the conversion from integer 0 to pointer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.