This question already has an answer here:
- Resolve build errors due to circular dependency amongst classes 9 answers
I have this file logger.hpp:
#ifndef _LOGGER_HPP_
#define _LOGGER_HPP_
#include "event.hpp"
// Class definitions
class Logger {
public:
/*!
* Constructor
*/
Logger();
/*!
* Destructor
*/
~Logger();
/*!
* My operator
*/
Logger& operator<<(const Event& e);
private:
...
};
#endif
And this file event.hpp
#ifndef _EVENT_HPP_
#define _EVENT_HPP_
#include <string>
#include "logger.hpp"
// Class definitions
class Event {
public:
/*!
* Constructor
*/
Event();
/*!
* Destructor
*/
~Event();
/* Friendship */
friend Logger& Logger::operator<<(const Event& e);
};
#endif
Well. In logger.hpp I include event.hpp and in event.hpp I include logger.hpp.
I need to include event.hpp because in logger.hpp I need to define the operator.
I need to include logger.hpp because, in event.hpp, of the friendship to be defined in the class Event.
Well this is, of course, a cyclic recursion.
I tried this:
1) In logger.hpp:
#ifndef _LOGGER_HPP_
#define _LOGGER_HPP_
#include "event.hpp"
class Event; // Forward decl
// Class definitions
...
Does not work. Compiler tells me that in event.hpp there is a not recognized type called Logger (and he is right of course):
ISO C++ forbids declaration of ‘Logger’ with no type
Compiler indicates me the line (in event.hpp) where there is the friendship declaration.
2) In event.hpp:
#ifndef _EVENT_HPP_
#define _EVENT_HPP_
#include <string>
#include "logger.hpp"
class Logger; // Forward decl
// Class definitions
...
Does not work. Compiler tells me that in logger.hpp there is a not recognized type called Event (and, again, it is right for obvious reasons):
ISO C++ forbids declaration of ‘Event’ with no type
Compiler indicates me the line (in logger.hpp) where there is the operator declaration.
Well... do not know how to face this? I tried everything, I put forward declarations everywhere, but, of course, they are not of any help. How to solve this??? (I suppose a best practice exists, better I hope so :) ).
Thankyou.