Search code examples
c++forward-declaration

'Cashier' was not declared in this scope


I have this piece of code

#ifndef STATION_H
#define STATION_H

#include <vector>
#include "Dispenser.h"
#include "Cashier.h"

//class Cashier;

class Station
{
private:
    int price;
    int dispenser_count;
    int cashier_count;
    std::vector<Dispenser> dispensers;
    std::vector<Cashier> cashiers;

public:
    Station(int, int, int);
    int GetPrice() const { return price; }

    Dispenser *LookForUnoccupiedDispenser(int &id);
    Dispenser *GetDispenserByID(int id);

    Cashier *LookForUnoccupiedCashier();
};

#endif // STATION_H

When I have the class Cashier line commented, the compiler fails with a 'Cashier' was not declared in this scope error even though Cashier.h was included. Uncommenting it makes it possible to compile but I'm concerned that it shouldn't be happening.

Cashier.h

#ifndef CASHIER_H
#define CASHIER_H

#include "Station.h"

class Station;

class Cashier
{
private:
    bool busy;
    Station *at_station;

public:
    Cashier(Station *employer);

    bool IsBusy() const { return busy; }
};


#endif // CASHIER_H

How is it possible? It's clearly declared in the header file and as far as I know, #include does nothing more than pasting the content of a file into another one.

Thank you for the answers in advance!


Solution

  • Your station.h includes cachier.h. This is an example of cyclic dependency. Given that you only have a pointer to Station in Cachier I'd suggest removing the dependency of station.h and forward declare it.

    An #include is literally nothing more than verbatim copy and paste of that file into the current compilation unit. The guards protect you from the effect of an infinite include cycle, but due to the guards one of the #includes does nothing, i.e. does NOT suck in the declaration (nor definition) of the respective class. This results in the error you get. In station.h the compiler has never seen any mention of the Cachier type when it sees the Station type.