Passing classes to functions

I know that it is possible to pass a class instance to a function, but in my experience, if said function changes any variables of the class, they don't actually get changed. For example, we have class object, that has a member int number = 5. Lets say we have two functions, func1() and func2, which are not members of class object. If we pass object to func1() which, lets say, increases number by 5 (so now number = 10), at the end of that function number still = 5. Is there a way to bypass this and have functions alter class variables permanently?

P.S. I know that I can pass variables by reference, but, in my experience, such a thing does not work with vectors (which I am also dealing with), so simple passing the desired variables by reference won't work.
P.S. I know that I can pass variables by reference,


That is the solution. Passing by value creates a copy. Modifying the copy does not modify the original.

When you pass by reference, it's like you are passing the original directly. Any changes made to the reference are made to the original because the original and the reference are one and the same.

but, in my experience, such a thing does not work with vectors


They work with vectors just fine. There is no difference between a vector and any other type.

so simple passing the desired variables by reference won't work.


Yes it will.


EDIT:

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <vector>
#include <iostream>
using namespace std;

void func(vector<int>& vec)
{
    // modify the vector
    vec.push_back(2);
    vec.push_back(3);
}

int main()
{
    vector<int> a;  // our vector
    a.push_back(1);  // add 1 element to it

    func(a);  // pass it to our function (by reference) to add 2 more

    // how many items?
    cout << a.size();  // will output 3
}



Output as shown from IDEOne:

http://ideone.com/K9bEWK
Last edited on
TsarLenin wrote:
I know that I can pass variables by reference, but, in my experience, such a thing does not work with vectors (which I am also dealing with), so simple passing the desired variables by reference won't work.
What makes you say this? Any type may be passed by reference, it is not even possible to prevent a type from being passed by reference.

What code did you try that gave you an error when you tried to pass a vector by reference?
I think I may have messed up in the parameter in the prototype. It would be something like function( vector<string> ); correct?
Look at line 5 of Disch's post that wasn't there when I wrote my post because he's a highly skilled ninja.
Ah, alright. Thank you!
Topic archived. No new replies allowed.