MainS
MainS

Reputation: 160

Forward declaration with Inheritance and include | incomplete type or expected class name

Can somebody help?

Suppose, I have the following C++ files:

Room.h

#ifndef ROOM_H
#define ROOM_H

#include "Console.h"

...

class Room {
public:
   void room();
};

#endif // ROOM_H

Room.cpp

#include "Room.h"

void Room::room() {
  Console::print();
}

Console.h

#ifndef CONSOLE_H
#define CONSOLE_H

#include "Room.h"
#include "RoomChild.h"

class Console {
public:
   static void print();
   static void printRoom(Room& room);
   static void printRoomChild(RoomChild& room);
};

#endif // CONSOLE_H

Console.cpp

#include "Console.h"

void Console::print() {
    ;
}

void Console::printRoom(Room& room) { 
    // print member of room 
}

void Console::printRoomChild(RoomChild& roomChild) { 
    // print member of roomChild 
}

RoomChild.h

#ifndef ROOM_CHILD_H
#define ROOM_CHILD_H

#include "Room.h"
#include "Console.h"

class RoomChild : public Room {
public:
    void roomChild();
};

#endif // ROOM_CHILD_H

RoomChild.cpp

#include "RoomChild.h"

void RoomChild::roomChild() {
    Console::print();
}

My questions is

Is it possible to make it working?

I have tried to put forward declarations to each class or to some of them only. However, it does not work and give me either ... has incomplete type, or expected class-name before '{' token class RoomChild: public Room {

Upvotes: 0

Views: 99

Answers (1)

Eljay
Eljay

Reputation: 5321

The includes are all goofed up.

Delete the superfluous include directives from the files where they are irrelevant.

Add include directives on the files where they are depended upon.

Room.h

#ifndef ROOM_H
#define ROOM_H

/* DELETE: because Room.h does not depend on it.
#include "Console.h"
*/

// ...

class Room {
public:
   void room();
};

#endif // ROOM_H

Room.cpp

#include "Room.h"

/* ADD: because Room.cpp does depend on it. */
#include "Console.h"

void Room::room() {
  Console::print();
}

Console.h

#ifndef CONSOLE_H
#define CONSOLE_H

/* DELETE: because Console.h does not depend on them.
#include "Room.h"
#include "RoomChild.h"
*/

class Console {
public:
   static void print();
};

#endif // CONSOLE_H

Console.cpp

#include "Console.h"

void Console::print() {
    ;
}

RoomChild.h

#ifndef ROOM_CHILD_H
#define ROOM_CHILD_H

#include "Room.h"
/* DELETE: because RoomChild.h does not depend on it
#include "Console.h"
*/

class RoomChild : public Room {
public:
    void roomChild();
};

#endif // ROOM_CHILD_H

RoomChild.cpp

#include "RoomChild.h"
/* ADD: because RoomChild.cpp does depend on it. */
#include "Console.h"

void RoomChild::roomChild() {
    Console::print();
}

Upvotes: 3

Related Questions