C++ constructor definition differences in the code given below

107 Views Asked by At

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?

1

There are 1 best solutions below

3
On

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