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.
#include <vector>
#include <iostream>
usingnamespace 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
}
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?