Function definition with default value (c++)

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.

Edit:

After reading the comments, I tried to run the following:

using namespace std;


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

class Derived : public Base{

public:
    void fun(){ cout << "Derived::fun()";}

};

int main(){
    Derived d;
    d.fun(1);
    return 0;
}

The program does not compile and the error I get is:

error: no matching function for call to 'Derived::fun(int)'

Why is this happening if calling if the base class compile perfectly fine?

>Solution :

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);

Leave a Reply