1

I'm trying to make gui (buttons, etc.) in Allegro, and I have some problems. So far there are three classes: screen, button, label. The (simplified) code looks like this:

gui.h:

class button;
class label;
class screen;    

class screen {
    typedef boost::variant< button*, label* > gui_element;
    std::vector<gui_element> elements;

public:
    ALLEGRO_COLOR background_col;
    void add(button *button) {
        elements.push_back(button);
    }
    void add(label *label) {
        elements.push_back(label);
    }

    class draw_visitor : public boost::static_visitor<>
    {
    public:
        void operator()(button *button) const
        {
            button->draw(); //C2027: use of undefined type 'button'
                            //C2227: left of 'draw' must point to class/struct/union/generic type
        }
        void operator()(label *label) const
        {
            label->draw();  //Same here
        }

    };

    void draw() {
        al_clear_to_color(background_col);

        for (u_int i = 0; i < elements.size(); i++) {
            boost::apply_visitor(draw_visitor(), elements[i]);
        }

        al_flip_display();
    }
};
#include "button.h"
#include "label.h"

button.h:

class button {
public:
    button(screen *scr)
    {
        scr->add(this);
    }
    void draw() {
    //draw the button
    }
};

(label.h is the same but with labels)

This code gives some errors (see the comments in the code).

Moving screen's definition after the #includes give a similar error, but inside button's and label's constructor: scr->add(this) Use of undefined type 'screen'; Left of '->add' must point to class/struct/union/generic type

So, how could I define them?

AstroRP
  • 267
  • 6
  • 15
  • 3
    variables and types should have different names. The declaration `button* button` is likely to cause problems. That's why class and variables usually use different conventions (ex: start with a lowercase for variables' names and an uppercase for classes' names). – Franck Aug 10 '16 at 18:52
  • 5
    Why don't you split *implementation* and *declaration* in different files, respectively *-cpp* and *.hpp*? You should avoid that kind of problems – BiagioF Aug 10 '16 at 18:53
  • Look up "forward declaration". And also "circular dependency". – Jesper Juhl Aug 10 '16 at 18:56
  • 2
    Use separate headers and implementation files. This ain't Java. (This is covered in your fine C++ book.) – molbdnilo Aug 10 '16 at 18:56
  • 1
    @Franck tried to change `button` (variable name) to `b` and so with label, that didn't do anything – AstroRP Aug 10 '16 at 18:58

0 Answers0