Access member from higher class

Hi,
I've made some classes that are somehow nested in each other.
This is a part of my code's structure:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//class1.h
#include "class2.h"

class Class1
{
public:
    Class1();
    Class2* GetX();
private:
    Class2 *x;
};

//class2.h
#include "class3.h"

class Class2
{
public:
    Class2();
    Class3* GetY();
private:
    Class3 *y;
};

//class3.h

class Class3
{
public:
    Class3();
    int GetNumber();
private:
    int number;
};


My problem is that I need to gain access from an object of Class3 to a function from Class1. Something like this:
1
2
3
4
5
6
7
8
9
//main.cpp
#include "class1.h"

int main(void)
{
    Class3 obj;
    obj->GetX();  // THIS IS WHAT I NEED TO DO
    return 0;
}
Use forward declarations to avoid includes whenever possible.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//class1.h
class Class2;

class Class1
{
public:
    Class1();
    Class2* GetX();
private:
    Class2 *x;
};

//class2.h
class Class3;

class Class2
{
public:
    Class2();
    Class3* GetY();
private:
    Class3 *y;
};

//class3.h
class Class1;

class Class3
{
public:
    Class3();
    int GetNumber();
    Class1* GetX();
private:
    int number;
};


In the source files you include the headers that are needed.
Your object of type Class3, obj, does not cause the creation of an object of type Class1. In your code above (although Peter87 shows alternative code), there is no way to call a GetX function of a Class1 object using only an object of type Class3.

Even using Peter87's code, note that you'll still have to make an object of type Class1 and organise its pointer to x.
Last edited on
¿what are you expecting that line to do?
I'm sorry, my main function wasn't really correct, instead of creating a Class3 object I create a Class1 object. In this Class1 object is a Class2 object and in here is a Class3 object.
I want to be able to call a function from Class1 when I'm working in the Class3 object.

1
2
3
4
5
int main(void)
{
    Class1 object;
    object->GetX()->GetY()->ExtraFunctionInClass3();   //THIS PART WORKS
}


How to I call the function GetX() from Class1 in ExtraFunctionInClass3()?
I need to do this because I need to be able to edit some variables from Class2.
Is this possible in any way?

@Peter87: Ok I've changed the header includes, thx ;)
Pass the object to the function (the variables that you want to change)
Also http://en.wikipedia.org/wiki/Law_of_Demeter

The dot '.' is the access operator
@ne555: If this is the only way I will try to implement it this way.

Thanks to everyone in this topic!
Topic archived. No new replies allowed.