When you have a class with no constructor defined, the compiler gives a default constructor for you. For example,
is essentially the same thing as
1 2 3 4
|
class Foo {
public:
Foo() { }
};
|
However, if you define your own constructor with parameters, but don't define a default (parameterless) constructor, the compiler will not make one for you.
1 2 3 4 5 6 7 8 9 10
|
// Example program
class Foo2 {
public:
Foo2(int a, int b) { }
};
int main()
{
Foo2 foo; // error: no matching function for call to 'Foo2::Foo2()'
}
|
Instead of creating a default constructor, I suggest using the initializer list as intended.
1 2 3 4
|
Game :: Game(Point topLeft, Point bottomRight)
: topLeft(topLeft), bottomRight(bottomRight),
board(topLeft, bottomRight)
{ }
|
Note: For initializer lists, the order matters.
For my example, the class should declare the member variables in the following order:
1 2 3
|
Point topLeft;
Point bottomRight;
Board board;
|
_______________________________
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
// Example program
class Point {
// ...
};
class Board {
public:
Board(Point topLeft, Point bottomRight) { }
};
class Game {
public:
Game(Point topLeft, Point bottomRight)
: topLeft(topLeft), bottomRight(bottomRight),
board(topLeft, bottomRight)
{ }
Point topLeft;
Point bottomRight;
Board board;
};
int main()
{
Game game(Point{}, Point{});
}
|