joncodo
joncodo

Reputation: 2328

Passing a variable to a class method

I have a method called update in a class called Man. In my main.cpp I call:

int age=0;
Man person;
person.Update(age);

This updates the person's age in the method. However, when I come back to the main file, it does not have an updated age. So the variable is set in the class method but not getting back to the main.cpp context.

EDIT

Man::Update(int age)
{
    age++;
}

Upvotes: 1

Views: 207

Answers (3)

asheeshr
asheeshr

Reputation: 4114

For a change in a variable to be reflected back in the calling scope, a reference to the variable has to be passed to the function. When a reference is passed, the variable in the function scope effectively refers to / is the variable in the calling scope.

Man::Update(int &age) //The ampersand reflects that it is a reference
{
    age++;
}

What you are doing is called passing by value. In this case, a new copy of the variable is created in the function scope and any changes made are not reflected back in the calling scope.

Look at this for a detailed explanation and this for a Q&A style explanation.

However, what you are doing in this specific case, does not require classes or member functions at all. It can be done using a single normal function.

Upvotes: 3

Joseph Mansfield
Joseph Mansfield

Reputation: 110648

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.

Upvotes: 2

Andrey Chernukha
Andrey Chernukha

Reputation: 21808

void Man::Update(int & age)
{
   age++;
}

it should work

Upvotes: 3

Related Questions