You are passing the age
argument by value. This means that it is copied into the function Update
and that copy is modified. You need to pass the argument by reference. This is easily done in C++ because it provides reference types. A name with reference type acts as an alias for the object that it is bound to. All you have to do is add an ampersand (&
) to your type:
void Man::Update(int& age)
{
age++;
}
When you do person.Update(age);
you are binding the object age
to the reference age
in your function.
Others may give you an alternative method using pointers (take an int*
argument and pass &age
to the function). This is how it would be done in C - but we're not writing C. Don't let them fool you! Taking a reference type is safer and more expressive than using pointers.
However, I question why you have a class called Man
and age
is not a member of Man
. Classes are a way to store related data together as an object. I would consider age to be part of the data that represents a man.