Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ OOP design - passing data member to other classes - is it reasonable? [closed]

Tags:

c++

I have one more question hopefully summerizing my thoughts.

Suppose I have the following 3 classes:

class Player:

class Player {
private:
    int positionX, positionY;
public:
    void move(Board& b) {
      // player changes its position on the board(move)
      b.removeCharFromBoard(positionX, positionY);
      positionX++;
      positionY++;
      // 'P' indicates a Player in the Board....
      b.insertCharToBoard(positionX, positionY, 'P');
    }
};

class Board:

class Board {
private:
    // BOARD_C and BOARD_R are both "#define ..." for some integer number.
    char board[BOARD_C][BOARD_R];
};

class GameEngine:

class GameEngine {
private:
     Board* board;
public:
     void playTurn(const Player& p) {
        p.move(board);
     }
};

is it seem reasonable to you that the GameBoard's playTurn function will call the Player's move function with the parameter "board"? I need to do it in order to mark in the board data member that the Player has changed his position. Is it keep the OOP basic rules?

Thank you all, Syndicator!

like image 793
SyndicatorBBB Avatar asked Jan 28 '13 21:01

SyndicatorBBB


1 Answers

Yes, in this case it seems to be reasonable (by "in this case" I mean "considering what I can guess about the semantics of your GameEngine and Board classes and the nature of their association/aggregation relationship"):

  1. Rather use a smart pointer than a raw pointer to hold the Board object in GameEngine. unique_ptr is probably what you want in this case, because all other aliases seems to be just observers and the lifetime of the board object is bound to the one of the GameEngine object. However, if shared ownership is needed, opt for shared_ptr. Just try not to use raw pointers, new, and delete, because they lead to buggy code;
  2. You still need to provide public functions on the interface of the Board class to modify the board, because Player won't be able to access its private member variables (and board happens to be one).
  3. Rather than #defines, use constexpr values for the sizes of the board (if you are using C++11). You might also want to consider Boost.MultiArray for creating safe bi-dimensional C-style arrays.
like image 197
Andy Prowl Avatar answered Sep 28 '22 02:09

Andy Prowl