Array of pointers to objects

Hi, I have a bunch of classes and objects, that I constantly have to implement into different functions. I wanted to simplify this and store pointers to the different object in an array, so that I only need to pass 1 array to the functions.
Is this even possible?

The code roughly looks something like this
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
27
28
29
30
31
32
33
#include <iostream>
using namespace std;

class RulesClass{}
class BoardClass{}
class ShipsClass{}

void SetUpRules(RulesClass*Rules)
void SetUpFleet(RulesClass*Rules,BoardClass*Board,ShipsClass*Fleet);
void Bomb(RulesClass*Rules,BoardClass*Board,ShipsClass*Fleet);
void NextRound(*ObjectArray); //just guessing how to implement here

int main(){
  RulesClass Rules;

  BoardClass BoardA[2] = {
      BoardClass(BoardSize,NoShips),
      BoardClass(BoardSize,NoShips),
  };
  ShipsClass Fleet;

  SetUpRules(&Rules);
  SetUpFleet(&Rules,(&BoardA)[2],&Fleet);
  Bomb(&Rules,(&BoardA)[2],&Fleet);

  /*and so on...
  I don't know the proper implementation so I'm just guessing below =)
  I would like to implimented something like this */

  ObjectArray[4]{&Rules,&BoardA)[2],&Fleet};

  NextRound(&ObjectArray)
}


Is it even possible to achieve this? What's the best implementation method?
Why not create a new class?

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
27
28
#include <iostream>

using namespace std;
class RulesClass {
    string somerule;
};
class BoardClass {
    string someBoard;

};
class ShipsClass {
    string someShips;

};
class GameClass {
    RulesClass Rules;
    BoardClass Board;
    ShipsClass Ships;
};

int main() {
    GameClass *aGame = new GameClass ();
    
    // do things 
    
    delete aGame;
    return 0;
}
Thanks Bdanielz, that should work =) How will I go about to access the object members directly from main?
Like this? aGame.Rules.getBoardSize();



Don't put something on the heap unless there is a good reason to. It takes time to find space on the heap when allocating, you have to remember to free it, and it takes time to mark the space free. In contrast, allocating space on the stack usually takes ZERO additional time (since the you're usually allocating space on the stack anyway, it just changes how much you move the stack pointer.

So I'd change Bdanielz's main() to
1
2
3
4
5
6
7
int main() {
    GameClass aGame;
    
    // do things 
    
    return 0;
}

Like this? aGame.Rules.getBoardSize();
With Bdanielz's code, it would be aGame.Rules.getBoardSize();. With my code it would be the way you have it.

Topic archived. No new replies allowed.