0

I have a quick question about including headers I'm in situation the I want to build 2 classes that both of them hold a pointer to the other class. Each of them is in different header. How can I including the headers in a way that I'll not get identifier error

Client.h

#ifndef CLIENT_H
#define CLIENT_H
#include "Viewable.h"

  class Client{
     Viewable *viewptr;
}
#endif

Viewable.h

#ifndef VIEWABLE_H
#define VIEWABLE_H
#include "Client.h"

  class Client{
     Client* client;
}
#endif

this code gives me identifier error coz there is double definition. I understand why, how can I avoid that error?

dor malka
  • 1
  • 5
  • 2
    I guess you meant to write `class Viewable` in your second code block... – wkl Apr 06 '17 at 07:28
  • 1
    Possible duplicate of [What are forward declarations in C++?](http://stackoverflow.com/questions/4757565/what-are-forward-declarations-in-c) – wkl Apr 06 '17 at 07:29
  • 1
    Possible duplicate of [Resolve header include circular dependencies](http://stackoverflow.com/questions/625799/resolve-header-include-circular-dependencies) – nwp Apr 06 '17 at 07:29

2 Answers2

0

make a new header file with both class in it:

#ifndef BOTH_H
#define BOTH_H

    class Client;
    class Viewable;

#endif

than include both.h to each of your header.

Sekkmer
  • 103
  • 1
  • 12
0

How can I include other header the already include my current header

You can not. There is no way to achieve this. It would create an infinite recursion of inclusions (which will prematurely terminate if you use header guards).

how can I avoid that error?

You will need to change your program so that there is no circular dependency, and so that you can remove one of the inclusions.

Actually, in the case of the example program, neither class actually depends on the definition of the other class, so neither needs to include the other. Replace the inclusions with declarations:

class Viewable;
class Client {
    Viewable *viewptr;

...

class Client;
class Viewable {
    Client* client;
eerorika
  • 232,697
  • 12
  • 197
  • 326
  • I want to add that `Client` can only hold a **pointer** to `Viewable` and `Viewable` can only hold a **pointer** to `Client`. You can't have a member "by-value" because the compiler at that point does not know the size of each other class, only the name of the class. – Alexander Stante Apr 06 '17 at 08:31