Question

I'm kinda new to C++ and I've run into a problem with setting up the main architecture. I learned how to use this specific architecture in C#, but I can't get it to work in C++. My problem is as follows: I have 2 objects. I want these objects to 'know' of each other, so I want references of both these objects as member variables inside themselves.

Consider this:

//main.cpp:
#include "Object1.h"
#include "Object2.h"

Object1 *obj1;
Object2 *obj2;

...

obj1 = new Object1(obj2);
obj2 = new Object2(obj1);

...


//Object1.h

#ifndef OBJECT1_H
#define OBJECT1_H

#include "Object2.h"

class Object1 {
    public:
    Object1(Object2*);

    Object2 *obj;
}

#endif


//Object2.h

#ifndef OBJECT2_H
#define OBJECT2_H

#include "Object1.h"

class Object2 {
    public:
    Object2(Object1*);

    Object1 *obj;
}

#endif

This however is impossible. Because without the ifndef thingy you'd have this endless iteration of including eachothers .h files. But with the ifndef one of the objects doesn't get the others class definition included and doesn't know what object it's supposed to create. This whole problem doesn't arise in C# because you don't have to include .h files. You don't even have .h files :P. When you make a new class every other class knows of this class's existence. But in C++ you have to include the .h of the specific class before it's possible to make an object of this class (or a reference even).

So, my question is. How do I make 2 objects with references to each other as member variables of themselves?

Thank you for your interest!

Cheers,

Maxim Schoemaker

Was it helpful?

Solution

You use a pre-declaration, which is just:

class Object1;     // Pre-declare this class, so we can have pointers to it

Object1 *object1;  // Works fine, without having the full declaration of Object1.

OTHER TIPS

To deal with the situation you described, in c++ , there is a thing called -Forward declaration.

A few useful links:

http://en.wikipedia.org/wiki/Forward_declaration

http://www-subatech.in2p3.fr/~photons/subatech/soft/carnac/CPP-INC-1.shtml

You do not need the #include in the header files. For example in Object1.h you can just put class Object2; instead. This has lots of advantages. Try to avoid #include in header files unless they do not compile without them.

You can do funky things like

class X;

X returnX();
void processX(X x);
    -

You don't need to include Object1.hpp in Object2.hpp if you are only working with pointers to Objects1. But you need to include Object1.hpp in Object2.cpp since it needs to have the actual implementation of Object1

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top