Reputation: 5055
I have the following structures with me.
typedef struct _abc{
int x;
int y;
} abc;
typedef struct _def{
abc a;
int b;
} def;
I want to read the abc
structure which is inside def
. I do it in the following way.
int main() {
def x;
x.a = abc(); // Initializing 'a'
std::cout << &x.a << std::endl;
abc y = x.a; // Accessing 'a' later
std::cout << &y << std::endl;
}
But from the console output I realized that the object reference is changed. That means the structure attribute is copied.
In the real-world scenario, structure abc
is large and making copies every time I access it will take a lot of time.
typedef struct _def{
_def(abc &_a){b=0;a=_a;}
abc &a;
int b;
} def;
int main() {
abc a;
def x(a);
std::cout << &x.a << std::endl;
abc y = x.a;
std::cout << &y << std::endl;
}
I tried this way also, but it gives me compile error.
Is there a way to access members of a class without copying them..?
Upvotes: 0
Views: 1902
Reputation: 691
You can directly access a structure inside a structure without building any additional construct for that.
To fix the compilation error, you have to initialize the reference via Initializer List.
typedef struct _def{
_def(abc &_a): a{_a} // a{_a} is the initializer list
{
b=0;
}
abc &a;
int b;
} def;
Or in case you need a shorthand for the member, you can create a reference to the member directly:
abc &y = x.a;
Upvotes: 4
Reputation: 385144
Yes, there is a way: references.
First, let's transform your program from C into C++ (your version is syntactically valid but represents an antiquated form of the art; we'll also add a missing header):
#include <iostream>
struct abc
{
int x;
int y;
};
struct def
{
abc a;
int b;
};
int main()
{
def x;
// No need for this at all; creating `x` already created `x.a`
// x.a = abc();
// Prints the address of `x.a`
std::cout << &x.a << std::endl;
abc y = x.a;
// Prints the address of the _copy_ of `x.a` that you just made,
// called `y`
std::cout << &y << std::endl;
abc& z = x.a;
// Prints the address of the `x.a` via a reference called `z`
std::cout << &z << std::endl;
}
As you can see from the above code, and from the demo, it is possible to declare a reference that acts as a new name for an existing object.
Please turn to the page in your introductory C++ book about references; they should be well explained therein.
Upvotes: 6
Reputation: 16404
You can use reference. Change
abc y = x.a; // Accessing 'a' later
to:
abc &y = x.a; // Accessing 'a' later
Then there is no copy.
Upvotes: 4