Home > other >  Function definition with default value (c )
Function definition with default value (c )

Time:02-01

Consider the following class:

class A{
public:
    void fun(int i=0) {cout<<"Base::fun("<<i<<")";}
};

If I understand correctly, when the compiler sees void fun(int i=0), it will define 2 functions for us. One is the function:

void fun() {cout<<"Base::fun("<<0<<")";}

And the other one is the function:

 void fun(int i) {cout<<"Base::fun("<<i<<")";}

Next, as I understand, we cannot define 2 functions with the same name in a class. For example:

class A{
public:
    void fun() {cout<<"Base::fun()";}
    void fun() {cout<<"Base::fun("<<0<<")";}
};

does not compile and returns error:

error: 'void A::fun()' cannot be overloaded with 'void A::fun()'

So, my question is why does the following definition compiles :

class A{
public:
    void fun() {cout<<"Base::fun()";}
    void fun(int i=0) {cout<<"Base::fun("<<i<<")";}
};

Thanks in advance.

CodePudding user response:

If I understand correctly, when the compiler sees void fun(int i=0), it will define 2 functions for us.

No you do not understand correctly. It only defines one single function returning void and taking an int parameter. Simply if you call it with no parameter and if not function with same name and declared with no parameter exists, the compiler will implicitely add the default parameter.

Said differently the compiler will under the hood replace this call:

fun();

with that one:

fun(0);
  •  Tags:  
  • Related