Pass object to constructor and work with the original

Hello,

this is my first post. Please excuse the - maybe - confusing title. Learning c++ in my native language. Translation seems hard sometimes.

I'm trying to create two objects "a" and "b". With creation of object "b" I want to use object "a". I also want to change the object "a" by using the public functions of object "b". See the code. I think it's getting clear.

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
#include <iostream>

class createObject {
	public:
		void input(int x) {
			a = x;
		}
		int display() const {
			return a;
		}
		void change(int x) {
			a = x;
		}
	private:
		int a;
};

class useObject {
	public:
		useObject(createObject& x)
		: o {x} {
		}
		void get() {
			std::cout << o.display() << std::endl;
		}
	private:
		createObject o;
		
};

int main() {
	createObject a;
	a.input(10);
	useObject b(a);
	b.get();				// returns 10
	a.input(12);
	b.get();				// returns 10, expected 12
	std::cout << a.display() << std::endl;	// returns 12
	return 0;
}


Can you give me a hint how to change the original object? I thought by working with "useObject(createObject& x)" i can do that.

Thanks!
Last edited on
The b.o is a createObject too. A copy constructed from a (on line 21).

Yes, you do use a reference parameter, but that just saves an additional copy.
If the x were by value, you would first copy a to x and then x to o.
The x as reference lets you essentially copy a to o directly.


The o could be a reference.
Thanks keskiverto. I guess i understood your explanation. The solution is just changing "o" to be a reference:

1
2
3
4
5
6
7
8
9
10
11
12
class useObject {
	public:
		useObject(createObject& x)
		: o {x} {
		}
		void get() {
			std::cout << o.display() << std::endl;
		}
	private:
		createObject& o;
		
};


The result is as expected 10, 12 ,12. But did I what you told me? ;-) Now i don't create a copy of "a" to "o" anymore, but i pass the reference of "a" to "o".
Last edited on
Topic archived. No new replies allowed.