When you pass variables to a function in C or C++ (unless you explicitly use C++ references), it copies that value. This is true for structs and classes as well.
Say we wanted to change a variable from another function:
#include <iostream>
void foo(int var)
{
var = 1;
}
int main()
{
int a = 0;
foo(a);
std::cout << a << std::endl;
return 0;
}
This will print "0" because when you pass "a" to the "foo" function, the value is copied, so the original variable "a" is left unchanged.
This is the same as in C#, except for classes, they are passed by reference implicitly in C#. To achieve the wanted behaviour in C#, you'd use the "ref" or "out" keywords.
In C++, you can use a pointer to achieve this:
#include <iostream>
void foo(int *var) //Receive a pointer to an int
{
*var = 1; //Dereference pointer and set value to 1
}
int main()
{
int a = 0;
foo(&a); //pass address of a to foo
std::cout << a << std::endl;
return 0;
}
But the preferred C++ way is to use references (In C, you don't have these):
#include <iostream>
void foo(int& var) //Receive a reference to an int
{
var = 1; //Set value referenced by var to 1
}
int main()
{
int a = 0;
foo(a); //pass a
std::cout << a << std::endl;
return 0;
}
References are better because they allow for a nicer, seamless syntax and they are a lot safer than pointers. References have a lot of restrictions on them (which is a good thing), so sometimes your only bet is to use a pointer. The general rule is; use pointers whenever you can't do it with references.
There is a lot more to pointers than this, but this is the typical case. For classes and structs you also want to use pointers or references to make them work like you'd expect in C# (see above posts for more on this).
The heap is also used when you want to create an array whose size isn't known until runtime.
In C99, you can create variable size arrays on the stack.