# C++ Include directives problem.

## Recommended Posts

Hi guys, I'm not sure if there is a solution to the problem I have, but I figured I'd give it a shot. Basically, I got two classes. In my case, I want both to have a copy constructor to eachother. But here comes the problem, I can't include Class1.h in Class2.h if Class1.h already includes Class2.h. And I can't forward declare because that only seems to work with pointers. I'm using MSVC #pragma and not include guards, but that doesn't seem to matter. CLASS1.H
#pragma once

#include "Class2.h"

class Class1
{
Class1 (Class2 &obj);
};

CLASS2.H
#pragma once

#include "Class1.h"

class Class2
{
Class2 (Class1 &obj);
};

Is there a solution to this at all? I haven't tried Precompiled Headers but it doesn't seem like it would help.

##### Share on other sites
Forward declarations:
CLASS1.H#pragma onceclass Class2;class Class1{    Class1 (Class2 &obj);};

CLASS1.CPP#include "Class1.h"#include "Class2.h"...

Equivalent for Class2.h and Class2.cpp.

This works fine as long you deal only with pointers or references to objects of a class. It doesn't work if you invoke a member, need to know the size of objects of that class, and similar things.

##### Share on other sites
In general, forward declarations should work fine with references.

What errors are you getting?

[Edit: Also, shouldn't those be constant references? Or is the argument actually modified in the constructor?]

##### Share on other sites
A forward declaration should do the trick here, they work for both pointers and references (a reference is, more or less, a nice wrapper around a pointer.)
So forward declare the other class in the header and include the other header in the cpp file. Like this:
class1.h#pragma onceclass Class2;class Class1 {public:    Class1( Class2 const& other );}

class1.cpp#include "class1.h"#include "class2.h"Class1::Class1( Class2 const& other ) {    ...}

and do the same with Class2. That should work.

##### Share on other sites
Bah! So forward declarations do work with references? I must have missed that and never tried myself. Thanks guys, ++!

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628305
• Total Posts
2981962

• 9
• 12
• 11
• 12
• 11