mchl12 mchl12 - 1 month ago 6
C++ Question

Error when creating an object with constructor

I ran into an error when using this code:

class Box {
public:
Box (int);
};

Box::Box (int a) {
//sample code
}

int main() {
class Anything {
Box box (5); // error: expected identifier before numberic constant
// error: expected ',' or '...' before numeric constant
};
}


The error appears on the five I filled in under class Anything.
The issue disappears if I just write.

Box box (5);


Without the Anything class around it.

Any help would be appreciated.

Answer

Inside Anything,

Box box(5);

is not valid for declaring the member variable and initializing it.

You can use:

class Anything {
    Box box;
    public:
       Anything : box(5) {}
};

or

class Anything {
    Box box = Box(5);
};

or

class Anything {
    Box box{5};
};