Why won't my constructor work?

I keep getting this error: no matching function for call to 'Board::Board()'
:topLeft(tl), bottomRight(br)
I'm not even sure what that's talking about. It looks more like my game constructor, not my board constructor.

Here is my Game constructor
1
2
3
4
5
  Game :: Game(Point tl, Point br) : topLeft(tl), bottomRight(br)
  {
     board = Board(topLeft, bottomRight);
     //etc.
  }


and here is my Board constructor
1
2
3
4
   Board :: Board(Point tl, Point br)
   {
      //etc.
   }


I have prototypes for both of these in their .h files, and they are identical to what is in the .cpp file. I don't know what the problem is.
When you have a class with no constructor defined, the compiler gives a default constructor for you. For example,
1
2
3
class Foo {

};

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{});
}
Last edited on
Topic archived. No new replies allowed.