Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function overloading -- two functions only differ by a default parameter

class A{
    public:
        void foo(int x)
        {
            cout << "foo with one\n";
        }

        void foo(int x, int y=10)
        {
            cout << "foo with two\n";
        }
};

int main()
{
    A a;
    a.foo(1);   //error?
}

So, why can't I overload void foo(int) with a function that takes a default parameter?

like image 936
Alcott Avatar asked Mar 30 '12 13:03

Alcott


1 Answers

No you cannot overload functions on basis of value of the argument being passed, So overloading on the basis of value of default argument is not allowed either.

You can only overload functions only on the basis of:

  • Type of arguments
  • Number of arguments
  • Sequence of arguments &
  • Qualifiers like const and volatile.

Ofcourse, Whether the overload is accepted by the compiler depends on the fact:
If the compiler resolve calling of the function unambiguously.

In your case, the compiler cannot resolve the ambiguity, for ex: The compiler wouldn't know which overloaded function to call if you simple called the function as:

 foo(100);

The compiler cannot make the decision and hence the error.

like image 85
Alok Save Avatar answered Sep 29 '22 07:09

Alok Save