0

I currently ran into a situation which I do not understand and would appreciate it if someone could explain to me why this is happening and how I may resolve it. Suppose I have two header files Client.h and Order.h with classes Client and Order respectively.This is an overview

FileName: Order.h

#ifndef Order_Header
#define Order_Header
.....
#include "Client.h"
class Order
{
  public:
  enum OrderType{open,close};
  Client db; // ---> Line A
};
#endif

FileName: Client.h

#ifndef Client_Header
#define Client_Header
.....
#include "Order.h"
class Client
{
  public:
  void someMethod(Order::OrderType e);
};
#endif

Now if this project is compiled I get an error at line A saying it does not recognize the Client Class. However If I move the enum from the Order Class to the Client class such that the enum is accessed using Client::OrderType then I get no errors. What is happening here any suggestions on how I can resolve this arent my header guards working ?

MistyD
  • 16,373
  • 40
  • 138
  • 240

2 Answers2

2

You have an circular dependency between client and order. Its best to try to avoid it. But if you need it you can forward declare your classes (and templates) and use references and pointers to them. The classes can not be used because they are incomplete.

#ifndef Order_Header
#define Order_Header

class Client; // forward declaration

class Order
{
  public:
  enum OrderType{open,close};
  // the following declarations work:
  Client* db_1;  
  Client& db_2;
  std::shared_ptr<Client> db_3;

  // the following declaration does not work, because of incomplete type
  Client db_4;
};
#endif

The same with Client.h. You should note that the declaration of your methods have to be changed from passing Client to Client const& as you cant use the incomplite type Client in your interface. Client&, Client*, std::shared_ptr<Client> and variations are complete types.

In your implementation files you can include all headers and your types are complete and you can work with them.

Jan Herrmann
  • 2,717
  • 17
  • 21
1

It's beacause when the compile the Order.h file he go first to the #include "Client.h" the it's compil it before Order.h and when he arrive to void someMethod(Order::OrderType e); Order is not defined. To solve it try

#ifndef Order_Header
#define Order_Header
.....
// #include "Client.h" Put it only on your cpp file

Class Client;
Class Order
{
  public:
  enum OrderType{open,close};
  Client db; ---> Line A
}
#endif

FileName: Client.h

#ifndef Client_Header
#define Client_Header
.....
#include "Order.h"
Class Client
{
  public:
  void someMethod(Order::OrderType e);
}
#endif

`

Zoruk
  • 41
  • 3