How to assign address of a struct to another struct?

Lets say I have

struct someStruct
{
    int a;
};

and 2 classes.

In the method in first class I create an instance of the structure:

someStruct structName;

now I want to pass the address of this struct to the constructor of another class

std::auto_ptr<2ndClass> 2ndClass_ (new 2ndClass(structName));

I want to use struct values changed in 2ndClass here - read below...

The second class has:

header:

...
class 2ndClass...
... 
private:
someStruct &structName2;
public:
__fastcall 2ndClass(someStruct &structName);
...

cpp:

__fastcall 2ndClass::2ndClass(someStruct &structName)
    : structName2(structName)
{
...

This obviously makes a copy of structName.

My question is: How can I assign an address to structName2 from structName so I can read and write into the structure, and then use those values in the first class after leaving the second class? How can I do it without using pointers to the structure?

Answers


This obvoiusly makes a copy of structName.

No it doesn't. You pass by reference, and your member is a reference, so 2ndClass::structName2 will refer to the exact object you pass as parameter to the constructor.

The question is how to assign address to structName2 from structName so I can read and write into the structure and then use those values in the first class after leaving second class.

You don't need to, since you work with references. In function signatures, & stands for reference, not address-of. So you don't pass the address, but the object itself.

Note that if the original structure goes out of scope, you'll have a dangling reference, so make sure to treat that case. It might appear to work if the memory isn't overwritten, but it's undefined behavior.


Need Your Help

Failed to ssh to machine after installing Docker

networking ssh

My ssh stops working after I successfully installed Docker (following the official site instruction https://docs.docker.com/engine/installation/) on an ubuntu machine A. Now my laptop cannot ssh to...