How to create dynamic objects in the member function?

advertisements

In a member function of Class Championship, I try to create dynamic objects and call the member function of Class Game, but I got the error message as error: expected primary-expression before '[' token. How to correct it?

class Championship
{
public:
    Championship(string,int);
    void CreateGame();
    void display();
 private:
    int gamenum;
};
class Game
{
public:
    friend class Championship;
    void Getteam();
};
void Championship::CreateGame()
{
    Game *game = new Game[gamenum];
    for (int i = 0; i < gamenum; i++)
        Game[i].Getteam();
}


The exact problem you are facing in your code is in this small bit

Game *game = new Game[gamenum];
for (int i = 0; i < gamenum; i++)
    Game[i].Getteam();

The main issue here is that you have declare an array of type Game and call it game but then you try to access using Game which is the type, so simply swapping that back to game would fix that issue.

However, there is no need for using raw pointers in this way. std::vector is superior in so many ways here. It allows you to dynamically add more and more objects into the container in a safe way. I was about to show how std::vector could be used in your Championship::CreateGame() function... but I can't really work out what it is trying to do...

I also don't see why you have the friend line in your game class... that is used to give another class 'full' access to your class, ie the Championship class is given access to private members of Game.