Exam 02.
class complex{
private:
float img;
float real;
public:
complex(float, float);
complex operator +(complex& p);//and here
};
In both examples, these methods can access to all data members of complex class (although private). We can change their data. Only one difference, in 1st, data of p nothing change, and 2nd changed. But if only that reason, why add const reference ? It has same purpose of 1st.
Personally, I avoid passing non-references because of the following reason:
When you don't pass by (const) reference / pointer, you copy the object. This means you don't really "use" the parameter, you make a new one for inside the function. This may not seem much of a big deal, but imagine copying a vector containing 60 string objects and passing it. Now imagine just allowing access to that object.
When you pass by reference, you pass a pointer, since a reference is just a wrapper for a pointer. This means that for built-in types, in which the pointer size equals the actual size, passing by reference or pointer doesn't help you anything at all.
Passing by value:
- Good because: no additional indirection involved in accessing the var/data memebers in the called function
- Bad because: object needs to be copied
Passing by reference:
- Good because: object does not need to be copied
- Bad because: accessing data members requires indirection.
For basic data types like float, double, int, etc, you're better off passing by value since the copy is cheap (just as cheap as passing a reference) and you avoid additional indirection.
For heavy complex types where you don't access member var directly (think encapsulated classes like vector, string, etc) you're better off passing by reference, because calling member functions already has indirection overhead, so having a reference is no slower than having a copy. Also, making a copy of complex objects can be expensive because they're so large.
For small data structures (like your "complex" class above) it's kind of a tossup, and you need to make a judgement call. Copying probably isn't very expensive, so passing by value could work. But there may not be much overhead for the indirection, so passing by reference might also be a good idea.