Need help creating pointer in a class that points to a separate variable.

I'm trying to find a way to create a pointer inside a class that points to an image variable that has already been created. That way instead of always passing the image to the class to work with it the class already knows what image to use by just using the pointer.

The first way I tried it wound up creating a new version of that image in memory for each class loaded which quickly bogged things down when many of the classes started popping up.

So now I'm looking for a way to have every class point to the same image in memory without making a new one every time.

Thanks,
Tyler
Make a pointer to that data type in the class, then in the constructor, let it point to the address of the variable. In that case, you would have full access to that variable, within the class.
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
using namespace std;


struct pixel
{
	float r;
	float g;
	float b;
	float a;
};

struct image
{
	pixel *PIXELS;
};

class Object
{
public:
	image* myImage;
	Object()
	{
		myImage = NULL;
	}
};


void main()
{
	Object myobj[2];
	int size;
	cin>>size;

	myobj[0].myImage= new image;
	myobj[0].myImage->PIXELS= new pixel[size];

	//myobj[1].myImage points to adress pointed by myobj[0].myImage
	myobj[1].myImage= myobj[0].myImage;

	//display myobj[0].myImage && myobj[1].myImage pointed adress
	cout<<myobj[0].myImage<<endl<<myobj[1].myImage;

	
	//delete pointers:
	myobj[1].myImage = NULL;
	delete[] (myobj[0].myImage->PIXELS);
	myobj[0].myImage->PIXELS =NULL;
	delete[] (myobj[0].myImage);
	myobj[0].myImage =NULL;

	cin.get();
	cin.get();
}
Last edited on
Ah ok thanks. I did not know I could use new from outside the class. That makes things a lot easier.

Thanks,
Tyler
Topic archived. No new replies allowed.