Jump to content
  • Advertisement
Sign in to follow this  
SymLinked

C++ Include directives problem.

This topic is 3042 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Bah! So forward declarations do work with references? I must have missed that and never tried myself. Thanks guys, ++!

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!