Creating an instance of a class inside a class (C ++)

Let's say I have two classes: Box, Circle.

class Box{
int x, y;
...Box(int xcoord, int ycoord){printf("I'm a box."); x = xcoord; y = ycoord;}
};

class Circle{
...Circle(){printf("I'm a circle.");}
};

But let's say in the Circle class, I want to make an instance of the Box class. Well, I tried this:

class Circle{
Box b(0,0);
...Circle(){printf("I'm a circle.");}
};

I get an error message:

error C2059: syntax error: constant

+3
source share
2 answers
class Circle {
    Box b;

public:
    Circle() : b(0, 0)
    {
        printf("I'm a circle.");
    }
};
+5
source

You are not allowed to create member variables in a class declaration. Justification are member variables that should not be used until the element has been built in any case, so they must be created in the constructor.

, Box() : x (0), y (0) {} . , ++ no-argument ( , ). Box, , . : Box, - Box . .

- . , , , , , .

class Box {
    public:
        int x,y;
        Box(int xcoord, int ycoord){printf("I'm a box."); x = xcoord; y = ycoord;}
        // Box() : x(0), y(0) {} Can do this, not advised.
};

class Circle{
   Box b;
   Circle() : b(0,0) {printf("I'm a circle.");}
};
+4

All Articles