-1

I'm relatively new to C++ and I'm facing this issue the whole day and it is really annoying . Assuming I have these 2 classes in seperate files a.hpp :

#ifndef A_H
#define A_H
#include "d.hpp"
#include <iostream>

class CPlay
{
public:
    CPlay() = default;
    CPlay(int m_money) { money = m_money;}
    void gameOn(int m_money, CRoom &a)
    {
        std::cout << "test";
    }
    ~CPlay() {}

private:
    int money;
};

#endif

and d.hpp :

#ifndef D_H
#define D_H
#include <iostream>
#include "a.hpp"
class CRoom
{
  public:
   CRoom() = default;
   CRoom(std::string m_Name , short m_Seats)
   {
       Name = m_Name;
       Seats = m_Seats;
   }
   void gameOff(int m_money , CPlay &a)
   {
       std::cout << "test2";
   }
  ~CRoom() {}
  private:
   short Seats;
   std::string Name;
};

#endif

and in the main prog :

#include <iostream>
#include "a.hpp"
#include "d.hpp"

int main()
{
   CRoom gameplay("GTA",5);

   return 0;
}

I keep getting this error

d.hpp:13:31: error: 'CPlay' has not been declared
    void gameOff(int m_money , CPlay &a)

I checked some documentation and realized that this has to do with the circular-dependency but I still couldn't fix the issue .

Some of the ticket that I checked had a problem with #define and #ifndef but that was not the case on my side .

Samir
  • 235
  • 1
  • 10

1 Answers1

1

To break the circular dependency, you need to add a forward declaration of the depended-on classes to each of your header files, like this:

#ifndef A_H
#define A_H
#include <iostream>

class CRoom;

class CPlay {
...

and:

#ifndef D_H
#define D_H
#include <iostream>

class CPlay;

class CRoom {
...

Note that this allows you to remove the #includes from the header files themselves.

Paul Sanders
  • 24,133
  • 4
  • 26
  • 48