Pointers/reference to objects

I was just curious how to make a pointer/reference to a class object in one function if the object was created in a different function.
The only work-around that I figured out so far is to make the object global, but I can see this getting very sloppy if I need to make a bunch of different objects.

Can anyone show me a bit of code that would do this, or a tutorial that would show me what to do?



Here is some code that creates an object and makes a pointer point at it.

1
2
3
4
void createObjectAndMakeThisPointerPointAtIt (someObjectType* thisPointer)
{
  thisPointer = new(someObjectType);
}


Something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>

class Foo
{
public:
int x;
void ChangeX(){x = 10;}
Foo():x(1){};
};

void NoRef(Foo temp)
{
temp.ChangeX();
}

void Ref(Foo &reference)
{
reference.ChangeX();
}

int main()
{
Foo a;
std::cout<<a.x<<std::endl;
NoRef(a);
std::cout<<a.x<<std::endl;
Ref(a);
std::cout<<a.x<<std::endl;
std::getchar();
}

In this example, the first function creates its own local copy of a. The second one, "Ref" uses a reference to a Foo object (Indicated by the '&'), which means that any changes done to the object passed inside the function will also take place outside it, since you are operating on the actual object you passed in, and not a copy of it.
Thanks, my code's working now, woohoo!
Topic archived. No new replies allowed.