Phillip Brandel
Phillip Brandel

Reputation: 95

Class function with parameter of same type as class

I am trying to write a chess engine in C++. I have a class gameState which stores the positions, types, and colors of the pieces, and has several functions to determine relevant information about the board, such as whether a given king is in check. It also has the function makeCopyOf(gameState g), which copies the parameter’s data to its own.

I am trying to write a function in gameState which tests for checkmate, and in order to do this I would like to copy its data into another temporary object of the same type. Is there a way to pass gameState as a parameter to one of its own functions? Some thing like this in JavaScript?

Upvotes: 0

Views: 762

Answers (2)

Tyler Ferraro
Tyler Ferraro

Reputation: 3772

It sounds like you're looking to write a Copy Constructor

This is similar to a constructor or initializer but takes the same class in as a parameter and creates a new class. For example, yours might look something like this:

class GameState {
  public:
    GameState(const GameState& g) {
      game_state_var_1 = g.game_state_var_1;
      game_state_var_2 = g.game_state_var_2;

      // ...
  }
};

Then in practice you would use it like this:

GameState g = GameState();
GameState duplicate_g = GameState(g);

It's also worth noting that if you're coming from a JavaScript background it's really important to know that JavaScript is a unique language. Neither functional nor object oriented, but pretending to be both. Before you write a new function in your class, take a moment to see if C++ supports overriding operations to do it first.

For example, you described your makeCopyOf(gameState g) function that you wrote for your GameState class. But a more idiomatic C++ approach would be to override the = operator like this:

class GameState {
  public:
    const GameState& operator=(const GameState& g) {
      game_state_var_1 = g.game_state_var_1;
      game_state_var_2 = g.game_state_var_2;

      // ....
      return *this;
    }
};

Which means you could just use an assignment operator to set the values of your GameState object to that of another GameState object, like this:

GameState g1 = GameState(1);
GameState g2 = GameState(2);

g1 = g2;
// g1 now has the same data as g2

Hope this helps, without any code its hard to directly answer your question.

Upvotes: 2

Phillip Brandel
Phillip Brandel

Reputation: 95

I realized almost immediately after posting that I could just use function overloading to define another makeCopyOf() without any parameters. This appears to have solved my problem.

Upvotes: -1

Related Questions