Search code examples
c++constructoroverloadingprivate

C++ - Constructor overloading - private and public


Can you tell me why the following code is giving me the following error - call of overloaded "C(int)" is ambiguous

I would think that since C(char x) is private, only the C(float) ctor is visible from outside and that should be called by converting int to float.

But that's not the case.

class C
{
    C(char  x)
    {
    }
public:
    C(float t)
    {
    }
};

int main()
{
    C p(0);
}

Solution

  • This is discussed in "Effective C++" by Scott Meyer. The reason this is ambiguous is that they wanted to ensure that merely changing the visibility of a member wouldn't change the meaning of already-existing code elsewhere.

    Otherwise, suppose your C class was in a header somewhere. If you had a private C(int) member, the code you present would call C(float). If, for some reason, the C(int) member was made public, the old code would suddenly call that member, even though neither the old code, nor the function it called had changed.

    EDIT: More reasons:

    Even worse, suppose you had the following 2 functions:

    C A::foo() 
    {
        return C(1.0);
    }
    
    C B::bar() 
    {
        return C(1.0);
    }
    

    These two functions could call different functions depending on whether either foo or bar was declared as a friend of C, or whether A or B inherits from it. Having identical code call different functions is scary.

    (That's probably not as well put as Scott Meyer's discussion, but that's the idea.)