-3

I am trying to write a simple game in C++ and currently have my Game_Window class holding an array of pointers to game objects as follows:

class Game_Window {
private:
    int width;
    int height;
    int num_objects;

public: 
    char** objects;

/* The rest of the class goes here */
}

Inside my Game_Window class I want to define a function that calls the "print()" function on all objects held in the game window "objects" array as follows.

void Game_Window::print_objects() {
    for (int i = 0; i < num_objects; i++) {
        (objects[i])->print();        /* THE PROBLEM IS HERE */
    }
}

When I compile I get the following error:

game_window.cpp:29:15: error: member reference base type 'char' is not a structure or union
                (objects[i])->print();
                ~~~~~~~~~~~~^ ~~~~~
1 error generated.

All objects in my game have a "print()" function so I know that's not the issue. Any help would be much appreciated.

smac89
  • 39,374
  • 15
  • 132
  • 179

2 Answers2

1

I think I figured it out. I created a class called Game_Object that all my game objects will inherit, and gave it a print() method.

class Game_Object {
private:
    Location location;

public: 
    Game_Object();

    Location *get_location() { return &location; }
    void print();
};

class Diver : public Game_Object {
public:
    explicit Diver(int x, int y);

};


class Game_Window {
private:
    int width;
    int height;
    int num_objects;

public: 
    Game_Object** objects;


    explicit Game_Window(int width, int height);
    ~Game_Window();

    int get_width() { return width; }
    int get_height() { return height; }
    int get_object_count() { return num_objects; }
    bool add_object(Game_Object object);    
    void print_objects();

};

The invocation of print() is now:

void Game_Window::print_objects() {
    for (int i = 0; i < num_objects; i++) {
        objects[i]->print();
    }
}

I ran it and it game me no errors.

0

The type of Game_Window::objects is char** (pointer to pointer to char). Hence objects[i] is the ith pointer, and pointers don't have print() methods, which is why (objects[i])->print(); fails with the described error.

Perhaps you meant to use print(objects[i]); instead?

jotik
  • 17,044
  • 13
  • 58
  • 123