0

can a struct member be a reference to another class? I have this struct in header file:

struct stop_object {
    timetable& tt;
    std::string stop_name;
    std::set<std::string> platforms;
};

and this class in header file:

using stop_container = std::vector<stop_object>;

class timetable {
    public:
    stop_container timetable_stops;
    platform_container timetable_platforms;
    platform_route_container timetable_platform_routes;
    route_departure_container timetable_route_departures;
    trip_container timetable_trips;
    trip_departure_container timetable_trip_departures;
};

I can not build the program. It says: missing type specifier. for timetable& tt; How can I achieve that I will have the reference to the parent object in which the struct is? Thanks for help!

Rikib1999
  • 199
  • 7
  • Yes, classes can store references. Please post a [mre] to get help with your error. Do note that having a reference member makes your class no longer copy/move assignable. – NathanOliver Jan 06 '21 at 15:17
  • Isnt there problem with cycle referencing? From class timetable to struct stop_object and so on... – Rikib1999 Jan 06 '21 at 15:21
  • 1
    See the duplicate link for *Resolve build errors due to circular dependency amongst classes* on how to fix the circular dependency. – NathanOliver Jan 06 '21 at 15:22
  • @Rikib161999 Yes there is. You can fix that by putting `struct timetable;` before `class timetable { ...`. – Paul Sanders Jan 06 '21 at 15:23
  • @PaulSanders there cant be struct and class with the same name – Rikib1999 Jan 06 '21 at 15:28
  • Soryy, I meant put `class timetable;` before `struct stop_object`. Apologies for the error. – Paul Sanders Jan 06 '21 at 15:53
  • Then I get error: the default constructor cannot be referenced when I want to initialize my struct – Rikib1999 Jan 06 '21 at 16:28
  • In adfdition to not being copy/move assignable, your class is also not default-constructible. Write a constructor that initializes it reference member. – Stephen M. Webb Jan 06 '21 at 19:22

0 Answers0