vienya
vienya

Reputation: 57

Forward declaration of inherit class

The programm below is about polymorphism. It just changes the status of a door between open and closed. My problem is that i can't switch the status in my class "Open" to closed since the class "Close" is below my class "Open".

How can i forward declare the class "Close" that it will work properly? (since a normal forward declaration like 'class Close;' doesnt seem to work)

class Status;

class Door {
    private:
        Status* currentStatus;
    public:
        void setStatus(Status*);
        void opendoor();
        void closedoor();
};

class Status {
    public:
        virtual void opendoor(Door* s)=0;
        virtual void closedoor(Door* s) = 0;
};

class Open : public Status {
    public:
        void opendoor(Door* s) {
            return;
        }
        void closedoor(Door* s){
            s->setStatus( new Close() ); //Error here
            return;
        }
};

class Close : public Status {
    public:
        void opendoor(Door* s) {
            s->setStatus( new Open() );
            return;
        }
        void closedoor(Door* s){
            return;
        }
};

void Door::opendoor() {
    currentStatus->opendoor(this);
    return;
}

void Door::closedoor(){
    currentStatus->closedoor(this);
    return;
}

void Door::setStatus(Status* x) {
    delete currentStatus;
    currentStatus = x;
    return;
}

Upvotes: 0

Views: 792

Answers (2)

vsoftco
vsoftco

Reputation: 56547

Define the member function that needs the full definition of Close after the full implementation of Close. For example,

void Open::closedoor(Door* s)

should be defined outside your class, after class Close. That's because in the line

s->setStatus( new Close() )

the compiler needs to know the full definition of Close, as it tries to constructs an object of type Close.

Upvotes: 1

Christophe
Christophe

Reputation: 73376

The easiest would be to separate the class from the implementation: first declare all the classes. Then only the implementation of the member functions.

class Status;
class Door {
    ...
};
class Status {
    ...
};

class Open : public Status {
    public:
        void opendoor(Door* s) override; 
        void closedoor(Door* s) override; 
};

class Close : public Status {
    public:
        void opendoor(Door* s) override; 
        void closedoor(Door* s) override; 
};
...
void Open::closedoor(Door* s){
     s->setStatus( new Close() ); //no more error here
     return;
}

Upvotes: 2

Related Questions