0

I'm trying to pass a class reference to a field, but I get the error "'mazeGenerator::maze' references must be initialized".

I tried initializing 'maze' above the class constructor.

Why is this happening?

class mazeGenerator {
public:
    Maze& maze;

    mazeGenerator(Maze& mazeObj) {
        maze=mazeObj;
    }
}


Fred
  • 750
  • 1
  • 7
  • 14
  • 1
    Learn the difference between _initialization_ and _assignment_. Your code is doing the latter. – Daniel Langr Jun 01 '20 at 12:27
  • 1
    Exactly what it says. A reference must be initialised (made to reference something) as it is created. The assignment `maze = mazeObj` assigns the value of the object referenced by `maze` the value of `mazeObj`. In classes, a reference member can only be initialised as the object is constructed, which is done in the constructor initialiser list `mazeGenerator(Maze &mazeObj) : maze(mazeObj) {}`. That ASSUMES the passed `mazeObj` was constructed in other code AND will continue to exist for as long as the `mazeGenerator` object does. – Peter Jun 01 '20 at 12:31

1 Answers1

1

You must initialize data members of reference type with a member initializer list, like this:

mazeGenerator(Maze& mazeObj) : maze(mazeObj) {}

This is also the case with const data members.

Note that putting the declaration of the data member above the constructor doesn't actually make any difference; it could be declared below as well.

Also, your data members (whether they are of reference type or not), should be private to the class.

cigien
  • 57,834
  • 11
  • 73
  • 112