Luca wrote:
Quote:
I have 2 questions:
>
1. Which one is the best: Returning member variables of the class by const
ref or returning by pointer?
>
e.g.:
>
Employee* GetEmployee() const;
Employee& GetEmployee() const;
>
2. Which one is best: Passing a variable by const ref or by pointer?
>
e.g.:
>
void SetSalary(Employee* e);
void SetSalary(const Employee& e);
Compare between
void SetSalary(const Employee* e);
void SetSalary(const Employee& e);
Now answers,
For return by pointer & reference
1) GetEmployee can't return NULL =use reference.
also you have operator overloading on Employee =highly advised to
use reference.
2) GetEmployee can return NULL, use pointer.
Same for Setters.
Two points to remember,
1) C++ promotes reference idea for pass by reference.
Thus Employee e;
SetSalary(e); promotes value e to reference e (highly advices,
generated a better code) , which it doesn't do automatically for
pointer.
2) Employee e = GetEmployee() ; demotes reference to value (highly
discouraged, causes all sorts of problem) , which it doesn't do for
pointer. The effect for missing one & can be catastrophic.
Thus, while passing by reference, just do it blindly. While
returning reference, don't forget to check. Compiler is not there to
complain this "mistake" which it will do for pointer.