Passing vs returning a class object

I can't seem to grasp when to choose which method to populate a class object.

Why would I choose one of the following ways of creating a class object and assigning values over the other? (I know this could be with/without pointers/references, just trying to get a handle on the general idea of which is better & why)


Method A

1
2
3
4
void LoadValues(MYCLASS myclass)
{
myclass.numA = 1;
}



Method B

1
2
3
4
5
6
7
MYCLASS LoadValues()
{
MYCLASS myclass;
myclass.numA = 1;

return myclass;
}


Thanks
The first method does not work.

It doesn't make much sense to set variables this way. Better to use the constructor and/or set methods:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

class Data
{
private:
	int i;
	
public:
	Data(int num)     { i = num;  }
	void set(int num) { i = num;  }
	int get(void)     { return i; }	
};

int main(void)
{
	Data me(4321);
	std::cout << me.get() << '\n';
	me.set(1234);
	std::cout << me.get() << '\n';
	return 0;
}
Why would I choose one of the following ways of creating a class object and assigning values over the other?
Your examples aren't quite correct, but I get what you're asking.

Returning an object, if your compiler isn't very smart, incurs in an extra copy. For potentially large objects this can be a waste of time, so in those cases it's better to pass by reference and modify the object.

IINM, C++11 addresses this problem with the introduction of move semantics. I.e. if a temporary object (such as the return value of a function) is assigned to another object that implements a special copy constructor (the move constructor), this other constructor is called instead.
Last edited on
Topic archived. No new replies allowed.