Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a variable as a "Class" datatype, without calling the "Class" constructor?

Forgive me if I'm just blatantly missing something, but I'm trying to make the transition from structs and c to classes and c++.

Heres what I'm trying to do:

A have a "Checkers" class and a "Board" class.

Now with structs, I could just create an array of Checkers in my "board.cpp" file by doing:

Checker checkers[2][12]

(0 and 1 for each side, 0-11 for each piece)

The problem is that with classes, doing the same declaration will attempt to call the "Checkers" constructor. I get this error: "error: no matching function for call to ‘Checker::Checker()’"

My Checker constructor deals with initializing an individual piece (like if it is on side 0 or 1, piece 0-11), so I didnt mean to call it there.

Is there a way to avoid this, or am I going about this the wrong way? Thanks.

EDIT: Or maybe I should just design the constructor to initialize an array of checkers? Can you even declare variables as a datatype of a class/object?

like image 224
kevin Avatar asked Jan 19 '26 06:01

kevin


2 Answers

You can either create a default constructor or have an array of Checker pointers and initialize them by dynamically allocation each Checker in the Board's constructor with the appropriate parameters. In the latter case, the constructor is not called until you allocate them.

like image 107
Max Shawabkeh Avatar answered Jan 20 '26 20:01

Max Shawabkeh


Create a default constructor. Then use an initial function. I do recomend you use STL vector.

like image 25
Charles Beattie Avatar answered Jan 20 '26 19:01

Charles Beattie