-2

I am newbie to C++. Learning constructors. Please refer to two codes mentioned below, and provide reason, why Code 2 is not working. Thanks.

Code 1:

#include <iostream>
using namespace std;

class Box
{
    int x;
public:
    Box::Box(int a=0)
    {
        x = a;
    }
    void print();
};

void Box::print()
{
    cout << "x=" << x << endl;
}

int main()
{
    Box x(100);
    x.print();
}

Code 2:

#include <iostream>
using namespace std;

class Box
{
    int x;
public:
    Box(int a=0);
    void print();
};

Box::Box(int a=0)
{
    x = a;
}

void Box::print()
{
    cout << "x=" << x << endl;
}

int main()
{
    Box x(100);
    x.print();
}

Why the code 1 is working but Code 2 is NOT working?

Bahubali
  • 141
  • 1
  • 2
  • 8

1 Answers1

5

For some odd reasons you are not allowed to repeat the default value for a parameter:

class Box
{
    int x;
public:
    Box(int a=0);
//------------^  given here
    void print();
};

Box::Box(int a=0)
//------------^^  must not be repeated (even if same value)
{
    x = a;
}
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
  • 1
    The reason is not that odd. Consider `Box(Foo a=Foo{}){}` and `Box(Foo a=Foo{}); Box::Box(Foo a=Foo{})`. Which `Foo{}` should be used to initialize `a`? – Zereges Jan 06 '17 at 16:10
  • @Zereges - Yes, I know it has to do with the context of evaluating the default value. But here `=0` always gives the same result, so it *could* have been allowed. But isn't. – Bo Persson Jan 06 '17 at 16:25
  • 2
    Would be somewhat strange if it worked for some values but not for others. Anyway, the header is where you want to show the default value, and why do redundant stuff? – Aziuth Jan 06 '17 at 16:37