Search code examples
c++c++11enumsforward-declaration

Forward Declaration of enum in a class?


I have two Abstract Classes which own each other a pointer of the other one. I need to use in one of them an enum of the other Class, like shown in the example. AFoo is holding ABar, and ABar need a pointer to AFoo to update some data and also a member function that going to use the AFoo enum.

I remember having this problem once but not with enum and I ended up doing inline declaration.

I could do a nested class, but is there another way to avoid that?

AFoo.hpp :

#include ...

class AFoo;
enum AFoo::poo; --> not possible

#include "ABar.hpp"

class AFoo {
public:
  ...
 virtual void func() = O;
 enum poo {
  H,
  I,
  ...
 }
protected:
 ABar *bar_;
};

ABar.hpp

#include ...

class Abar;

#include "AFoo.hpp"

class ABar {
public:
 ...
 virtual AFoo::poo doing_some_stuff() = 0; --> Here is my problem (if I replace the return type with basic type I have no compilation problem)
protected:
 AFoo *foo_;
};

Solution

  • In AFoo.hpp, don't include ABar.hpp, only forward declare the class:

    class ABar;
    

    Also, in ABar.hpp, include AFoo.hpp and don't forward ABar or AFoo.