A brief insight on 'by-reference', followed by a few notes on your code above:
When we pass an argument to a function by reference, or return an argument from a function by reference, we in essence pass/return the argument's address.
This address is typically a 4-byte variable on 32-bit systems and an 8-byte variable on 64-bit systems.
So in terms of run-time performance, passing/returning an argument by reference is exactly as passing/returning an argument as pointer. In both cases, a 4-byte / 8-byte value is copied into the stack.
The main advantage of 'by-reference' over 'by-pointer' is during compile-time, when it allows us to refer to the argument directly instead of indirectly. In other words, it allows us to use .
instead of ->
, and it relieves us from the need to use *
.
This proves useful mostly with template classes and functions, which may operate on generic objects.
In contrast, the main advantage of 'by-reference' over 'by-value' is during run-time, in the amount of data being copied into the stack every time an argument is passed to a function or returned by a function.
So while there's an advantage in passing/returning a structure by reference (constant or non-constant), there is no advantage in passing/returning a native variable such as int
by reference when it's constant. The amount of data copied into the stack is the same whether we pass it by reference or by value. So if this variable is not supposed to change, then we can simply pass/return it as int
instead of as const int&
.
Now just a couple of notes (deriving from the above) on your code:
In the Person()
constructor, you can pass the arguments as int
instead of as const int&
.
In the getName()
function, you should return const string&
instead of as string
.
An additional (unrelated) note:
You've declared operator==
as a member function of class Person
.
If you intend to keep it there, then you might as well declare this function const
.
However, you might wanna consider declaring it as a global friend
function, in order to allow comparison with an object of some future class, which could be cast to Person
. Declaring this operator as a global function will allow you to make the comparison "on both sides" (A == B
or B == A
).