References in data structures

Im creating a data structure called button. Most of its elements are just old-fashioned data types, except the last one, which is supposed to be a reference to a boolean variable I pass it later:

1
2
3
4
5
6
7
8
struct button {
int x;
int y;
int width;
int height;
char* text;
bool &pressed;
};


When I try to create a variable using this structure, I get the error "no appropriate default constructor available". If I comment out the reference in the structure, the error is fixed. So I know thats where the issue is. Is there anything I can do to fix this error?
References must be initialized at instantiation time. To fix this, you would
need to define a constructor for button that takes a bool by reference:

struct button {
explicit button( bool& b ) : x(), y(), width(), height(), text(), pressed( b ) {}
... Rest of your struct here ...
};

Think of a reference as a pointer that can never be NULL or uninitialized:
it always _has_ to point to some boolean.

If you can't supply the bool at construction time, then you'll need to
make it a pointer.
Topic archived. No new replies allowed.