1

I am trying to access a variable which is inside of an object (TestClassThree.h) which is inside the parent class (TestClassOne.h). Each class is in its own file, and when I try to import the files to instantiate the classes it crashes. I suspect it is because of import loops. I don't think that I can use forward class declarations, because that would restrict the access to the variable. How can I access the variable inside of TestClassThree from TestClassTwo?

//--TestClassOne.h--
#include "TestClassTwo.h"
#include "TestClassThree.h"

class TestClassOne {
public:
    TestClassTwo *myVariable;
    TestClassThree *mySecondVariable;

    TestClassOne() {
        myVariable = new TestClassTwo(this);
        mySecondVariable = new TestClassThree();
    }
};

//--TestClassTwo.h--
#include "TestClassOne.h" //<-- ERROR

class TestClassTwo {
public:
    TestClassOne *parent;

    TestClassTwo(TestClassOne *_parent) : parent(_parent) {

    }

    void setValue() {
        parent->mySecondVariable->mySecondVariable->value = 10;
    }

};
Sosumi
  • 759
  • 6
  • 20

3 Answers3

1

you can use forward class declarations and friend Keyword

Patato
  • 1,464
  • 10
  • 12
1

Try adding a so-called include guard (cf. this SO question). In TestClassOne.h add the following lines at the top and bottom of the file:

#ifndef TESTCLASSONE_H
#define TESTCLASSONE_H

[...]

#endif

Add this also to TestClassTwo.h, but change the name of the preprocessor macro to TESTCLASSTWO_H.

Community
  • 1
  • 1
herzbube
  • 13,158
  • 9
  • 45
  • 87
0

Both what said herzbube and patato answered your question :

1 - Avoid "includes loops" using #ifndef / #define macros just like herzbube explained

2 - Use forward classes declarations to tell the compiler a class will be defined after

// 1- avoid "include loops"
#ifndef TESTCLASSONE_H
#define TESTCLASSONE_H

// 2- Forward classes declarations
class TestClassTwo;
class TestClassThree; // assuming TestClassThree needs TestClassOne.h

class TestClassOne{
...
};
#endif
Laurent
  • 812
  • 5
  • 15