Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ ERROR: forward declaration of 'struct...?

cyclical inclusion problem

I forward declare one of the classes in the header of the other in an attempt to solve their cyclical inclusion. Here are my two files:

The first file (Parameter.h):

#pragma once
#include "Token.h"`

class Expression;

class Parameter {
public:

    Parameter() {
        string = new Token();
        identifier = new Token();
        expr = new Expression();
    }

    Token* string;
    Token* identifier;
    Expression* expr;
};

The second file (Expression.h):

#pragma once
#include "Token.h"
#include "Parameter.h"

class Expression {
public:
    Expression() {
        param1 = new Parameter();
        param2 = new Parameter();
        op = new Token();
    }

    Expression(Parameter* p1, Token* o, Parameter* p2) {
        param1 = p1;
        param2 = p2;
        op = o;
    }

    Parameter* param1;
    Parameter* param2;
    Token* op;
};

As you can see, I forward declare Expression in Parameter.h, but I'm still getting the following two errors:

forward declaration of 'struct Expression'

invalid use of incomplete type 'struct Expression'

I looked a several previously posted questions but still, couldn't solve this problem. Thanks.

like image 512
amorimluc Avatar asked Dec 07 '22 09:12

amorimluc


1 Answers

You can't forward declare Expression because you need the full declaration for this:

Parameter() {
    string = new Token();
    identifier = new Token();
    expr = new Expression();  // here!
}

What you can do is move the implementation of the Parameter() constructor out of the header and into a .cpp file.

like image 83
juanchopanza Avatar answered Dec 09 '22 13:12

juanchopanza