Sign in to follow this  
SymLinked

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 this post


Link to post
Share on other sites
Forward declarations:

CLASS1.H

#pragma once

class 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 this post


Link to post
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 this post


Link to post
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 once

class 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 this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this