Home > Back-end >  Avoiding circular references with forward declarations, but unable to access class members
Avoiding circular references with forward declarations, but unable to access class members

Time:11-03

So, I've got several classes, two of which need to reference each other. I solved circular references with forward declarations in Entity.h, just included Entity.h in my Timeline.h class declaration. Entity has a subclass Human which would hopefully call a method in Timeline which is timeline->addEvent(...).

Timeline.h

#include <queue>
#include "Event.h"

class Timeline {
private:
    std::priority_queue<Event> events;
    long unsigned int currentTime = 0;
public:
    Timeline() = default;
    ~Timeline() = default;

    void addEvent(long unsigned int timestamp, EventType type, Entity *entity);
    void processEvent();
    void getCurrentTime();
};

Event.h

#include "Entity.h"

class Event {
private:
    long unsigned int timestamp;
    EventType type;
    Entity *entity;
public:
    Event(long unsigned int timestamp, EventType type, Entity *entity);
    ~Event() = default;
    long unsigned int getTimestamp();
    EventType getType();
    Entity *getEntity();

    bool operator<(const Event &rhs) const;
    bool operator>(const Event &rhs) const;
    bool operator<=(const Event &rhs) const;
    bool operator>=(const Event &rhs) const;
};

Entity.h

class Event;
class Timeline;

class Entity {
protected:
    Timeline *timeline;
    long unsigned int currTimestamp;
public:
    explicit Entity(Timeline *timeline, unsigned int age);
    virtual void processEvent(Event event) = 0;
};

Human.cpp (calls timeline->addEvent(...))

void Human::sleep(Event event) {
    Animal::sleep(event);
    unsigned int timeBlock = 96;
    this->timeline->addEvent(this->currTimestamp   timeBlock, EventType::AWAKEN, this);
}

And error logs

error: invalid use of incomplete type ‘class Timelinethis->timeline->addEvent(this->currTimestamp   timeBlock, EventType::AWAKEN, this);

note: forward declaration of ‘class Timelineclass Timeline;

I guess I'm just confused on why this would be an issue. It was fine using forward declaration when it was just class Event; but as soon as class Timeline; was added in order to implement addEvent() to Entity, it goes full fail. Any suggestions?

CodePudding user response:

Forward declaration only works if you have pointer member, but not actually trying to dereference it.

From a look at your code structure, if Human is subclass of Entity, then in the source code of Human.cpp where you dereference the pointer to Timeline, you need to actually include Timeline.h (instead of fw declaration of it).

  • Related