Direct access to members of struct

I am new to C++ struct.
Suppose I have a struct and a declaration:
1
2
3
4
5
struct triple{
int x, y, z;
};

triple foo;


How do I access foo.x, foo.y, foo.z without writing foo. (eg. only write x, y, z)

Last edited on
Not possible; or, at least, not in any convenient way that would accomplish the spirit of what you want. You're accessing the data members of the structure "foo" so you need to specify that that's what you're doing. If you were to just write "x" "y" or "z" then you'd be accessing a variable in the local scope called that, rather than the variables that belong to the object foo.

Consider if you wrote

triple foo, foo2;

Each one of foo and foo2 have their own x, y and z. If you were to write just x y or z there would be no distinguishing which one you're referring to.

In short, you'll just have to learn to use (and appreciate) C++'s method of distinguishing variables, or forgo the structure altogether and just declare them as local variables. (Something which would only be situationally appropriate.)
Don't fight it. It only gets worse when you encapsulate objects inside objects.

While it's far too trivial to actually use in this case, you can use a reference. This is something I do use when dealing with over large, deelply nested structures which require me to use some or other subelement multiple times for a calculation. Not nice... (When I code, I use classes and let them do their own calculations!)

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
37
38
39
40
41
42
43
44
#include <iostream>
using namespace std;

inline int sqr(int val) {
    return val * val;
}

struct triple {
    int x;
    int y;
    int z;
};

int myCalc_with_refs(const triple& foo) {
    int res = 0;

    const int& x = foo.x;
    const int& y = foo.y;
    const int& z = foo.z;

    res = sqr(x) + sqr(y) + sqr(z);

    return res;
}

int myCalc_normal(const triple& foo) {
    int res = 0;

    res = sqr(foo.x) + sqr(foo.y) + sqr(foo.z);

    return res;
}

int main() {
    triple bar = {3, 2, 1}; // we're back in the room

    int ret_1 = myCalc_with_refs(bar);
    int ret_2 = myCalc_normal(bar);

    cout << "ret_1 = " << ret_1 << endl;
    cout << "ret_2 = " << ret_2 << endl;

    return 0;
}


And, for completeness...

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
#include <iostream>
using namespace std;

inline int sqr(int val) {
    return val * val;
}

class triple {
private:
    int m_x;
    int m_y;
    int m_z;

public:
    triple(int x, int y, int z)
    : m_x(x), m_y(y), m_z(z) {
    }

    int doOwnCalc() const {
        int res = 0;

        res = sqr(m_x) + sqr(m_y) + sqr(m_z);

        return res;
    }
};

int main() {
    triple bar(3, 2, 1);

    int ret = bar.doOwnCalc();

    cout << "ret = " << ret << endl;

    return 0;
}

Last edited on
Topic archived. No new replies allowed.