mchl12
mchl12

Reputation: 321

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.

Upvotes: 1

Views: 1301

Answers (2)

R Sahu
R Sahu

Reputation: 206567

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

Upvotes: 5

Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33864

The reason for this is because box here:

 class Anything {
    Box box (5);
 };

Is not an object, it is a member of the class anything. You need to initialize it in the constructor (see here). If you want to be able to create a box you would need to do something like this:

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

Then you can create an anything object as such:

Anything anything;

And it will contain a Box object box initialized with 5.

Of course all of this is pointless because you cant actually do anything with Anything. It has no other data members or functions ...

Upvotes: 0

Related Questions