Popo Heche
Popo Heche

Reputation: 75

Header files, foward declaration

I was codding my project and i have come across this problem. I have 2 header, each one with a class, that needs the other, as you can see below.

I thought that this was just needed the use of foward declaration, but still doesnt work. Im out of Ideas.

Looking for Help :D

Headers , Main , and compiler erros listed bellow:

Header 1

#ifndef OBJ2_H
#define OBJ2_H
#include "obj1.h"
class obj1;

class obj2{
public:
    obj1 e;
};

#endif // OBJ2_H

Header 2

#ifndef OBJ1_H
#define OBJ1_H
#include "obj2.h"
class obj2;

class obj1
{
    obj2 e;
};

#endif // OBJ1_H

Main

#include <iostream>
#include "obj1.h"
#include "obj2.h"
using namespace std;

int main()
{
    obj1 class1;
    obj2 class2;
    cout << "Hello world!" << endl;
    return 0;
}

Error:

Upvotes: 1

Views: 77

Answers (1)

Nikita Smirnov
Nikita Smirnov

Reputation: 862

In this situation circular dependy make no sence. But if you remove it, problem with declarations would still be present. After you write a forward declaration, your original declaration from the header file is being redeclared. Actually, forward declarations are used to avoid including file into another header. So you just need to write class obj1; before declaring obj2 and include obj1.hpp in obj2 source file (.cpp). Still, forward declaration works only if you use those objects by reference or a pointer. In your code

class obj1
{
    obj2 e;
};

obj2 is composed by value, so it wouldn't compile with forward declaration. You need to remove it and leave only header inclusion.

P.S. sorry for 'declaration' word which appears too often

Upvotes: 2

Related Questions