Init
Init

Reputation: 81

Creating an instance of a class within 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:

error C2059: syntax error : 'constant'

Upvotes: 4

Views: 6000

Answers (2)

Marty B
Marty B

Reputation: 243

You are not allowed to instantiate member variables in the class declaration. The reasoning is the member variables should not be used until the item is constructed anyway, hence why they must be instantiated in a constructor.

The code from the semicolon to the opening brace of the constructor, Box() : x(0),y(0) {} is called an initializer list and is used to initialize the variables to default values before the code in the constructor's block is called. If variables are not initialized in this list, C++ will call the no-argument constructor to initialize them (or in the case of built-in data types, do nothing). You did not specify a no-argument constructor for the Box class so it remained uninitialized in the circle class which caused the error. There are two obvious ways you can go about fixing this, either define a no-argument constructor for Box, or initialize the Box member variable in the circle constructor's initializer list. The second method is always preferred.

Using initializer lists in constructors is a good habit to develop. If you wait to initialize big objects in the constructor's code block, you are effectively paying for the construction twice since you are first calling the objects no-argument constructor before entering the code-block and then again calling a constructor to initialize the variable to the state you want.

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.");}
};

Upvotes: 5

Fred Larson
Fred Larson

Reputation: 62073

class Circle {
    Box b;

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

Upvotes: 6

Related Questions