c++forward-declarationobject-composition

Access member of composition class c++


I have the following code, there is an 'Face' class which is composed of an 'Eyebrow' class. The expression of the face can be changed to one of the allowed public enums, thus controlling how each of it's constituent should be changed. Each of the constituent classes should be responsible for responding to a changed expression which is why I want to pass that along to each constituent.

face.h:

#include "eyebrow.h"
class Face {
    public:
        enum Expression {NEUTRAL, JOY, ANGER};
        void setExpression(Expression);
    private:
         Eyebrow left_eyebrow;
}

face.cpp:

#include "face.h"
#include "eyebrow.h"

void Face::setExpression(Expression e) {
     left_eyebrow.setExpression(e);
}

eyebrow.h:

#include "face.h"

class Eyebrow {
    public:
         void setExpression(Face::Expression);
};

The code is being compiled with Cmake:

add_executable(Main main.cpp face.cpp eyebrow.cpp)

I am getting the following compiler error: ‘Face’ has not been declared in void setExpression(Face::Expression_e) in eyebrow.h.

I then forward declared Face (see below) and got the compiler error: ‘Face::Expression’ has not been declared in void setExpression(Face::Expression); in eyebrow.h

eyebrow.h (with forward declaration):

#include "face.h"

class Face;
class Eyebrow {
    public:
         void setExpression(Face::Expression);
};

What is the recommended way of solving this, should friends be used?


Solution

  • You have created a circular dependency:

    face.h includes eyebrow.h and eyebrow.h includes face.h, so they're including each other. You must resolve the circular dependency.

    You could remove the enum from Face and put it in its own header file, which both files could then include.

    Alternatively, you could store a pointer to Eyebrow in Face instead of Eyebrow itself. Then you could remove the include of eyebrow.h in face.h and forward-declare Eyebrow instead. The pointer can then be initialized in the constructor of Face.