C++ class variable access

Pages: 12
Hey all, I have made a class to store a tile-based map for a game.

Every time i try to access a variable or element from inside a class, it gives me a wierd number (like when i try to access x, it gives me 213413423 instead of 640).

1
2
3
4
5
6
7
8
9
10
11
12
class defineMap
{
	public:
	void loadChunk(int x, int y, char* filePath);
	void unLoadChunk(int x, int y);
	void loadTextures(char* fileName);
	void drawMap(SDL_Surface* screen);
	chunk map[maxLoad * maxLoad];
	//void defineMap::loadMap(SDL_Surface* screen);
	private:
		vector<texture> textures;
};


chunk struct
1
2
3
4
5
6
7
8
9
10
11
12
struct chunk
{
	//Check whether this chunk is 'in use', if = to 0, it means that this chunk is unloaded, 1 = loaded
	int inuse;

	//x and y of the chunk
	int x;
	int y;

	//The chunk itself
	char map[chunkSize][chunkSize];
};


here is the loadChunk function i use to get things from files and store them in 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
void defineMap::loadChunk(int x, int y, char* filePath)
{
	//this will determine which chunk to load into!
	int whichChunk;

	//Check the various chunks in the map to see whether they are in use
	for (int i = 0; i < (maxLoad * maxLoad); i++)
	{
		if (defineMap::map[i].inuse != 1)
		{
			whichChunk = i;
			break;
		}
	}

	//Set the chunks x and y so we know where to put it!
	defineMap::map[whichChunk].x = x;
	defineMap::map[whichChunk].y = y;

	//for the while loop!!
	int i = 0;
	int j = 0;

	char tempChar;

	//Create file stream and read the file
	FILE* mapFile;
	mapFile = fopen(filePath, "r");

	//Actually read the file
	while (!feof(mapFile))
	{
		tempChar = fgetc(mapFile);

		if (tempChar == '\n')
		{
			j++;
			i = 0;
		}
		else if (!feof(mapFile) && tempChar != -1)
		{
			defineMap::map[whichChunk].map[i][j] = tempChar;
			printf("CHAR: %c and %c\n", tempChar, defineMap::map[whichChunk].map[i][j]);
			i++;
		}
	}
	fclose(mapFile);
}


I think its a simple syntax error that im not aware of, but what are the simple ways of accessing a class variable, some code would be nice! :D

much appreciated, super stinger
Hi super stinger,

Have you tried using the debugger to step through & watch you r variable values?

Mind you does it compile? if not post compiler output.
Also I presume that you have created a defineMap object. if you used new or otherwise created a pointer to it, then you should be able to use the pointer to access chunk, which is your only member variable.

Hmm ok, i did do the watch thing, and it also showed wierd values, though i will try pointers!

sorry TheIdeasMan, but how do i use pointers with this?
Last edited on
Can you post the code that calls defineMap::loadChunk ?

wondering whether you have:

Created the object
Initialised the member variables
do something with them
Why don't you save the Map Size into your file and read it to know its size?
That would be easier, also for user-created maps, as user will not have to input map size.

Also initialize all variables to 0 in your constructor (Make one).
EssGeEich: yes, this code is designed for this, the reason i load chunk is so that chunks can be generated on the go instead of just loading a 1 gb map all at once :)

TheIdeasMan: Heres there Code! - This is in the main function btw
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
			if (mapLoaded == 0)
			{
				//declare the class 'map'
				defineMap map;

				//randomize a map and put it in the variable class 'map' and put it in a file
				randomizeNewMapToFile("map1");

				//Load textures
				map.loadTextures("colours.txt");

				printf("TEXTURES LOADED\n");

				//Load the map
				for (int i = 0; i < (maxLoad); i++)
				{
					for (int j = 0; j < (maxLoad); j++)
					{
						sprintf(buffer, "map1/%i-%i.txt", i, j);
						printf("PATH: %s\n", buffer);
						map.loadChunk(i, j, buffer);
					}
				}

				printf("MAP LOADED\n");

				//finally draw the map
				map.drawMap(screen);

				printf("MAP DRAWN\n");

				//show the screen
				SDL_Flip(screen);

				mapLoaded = 1;
			}
Last edited on
Ok, sorry, ignore my post-
oh and btw, how do i make a constructor and what is its purpose, ive seen it before but never understood it
sprintf(buffer, "map1/%i-%i.txt", i, j);

Should this be:

1
2
sprintf(buffer, "map1/%i-%j.txt", i, j);
 


This is another reason why I never use single letters for variable names. If you do a find replace & change i to Row and j to Col, then this error would show up straight away.

I am guessing it's an error, because buffer is used by loadChunk, then possibly by drawMap.

When you debug, watch the variable values, see where they become wrong, then work backwards to see where they are set incorrectly.

EssGeEich is right - you need a constructor
I dont understand what you mean by the sprintf, doesnt %i mean 'represent as integer', i dont understand.

Ill try some backtracking, cheers
sorry my really bad. Not thinking straight at all.
haha i see, thats alright, someones been working too hard >_<

oh and can you tell me bout constructors by any chance?
Well, you need to google it, for a full explanation.


*** IGNORE FROM HERE ***
Well, a sprintf is like a printf to string.
So if you put a sprintf(buffer, "Hello") it will copy Hello to buffer.
But you can also add numbers!!
You can do it like:
sprintf(buffer, "The number is: %d", Number)
Yes, %d (also %i) represent a int.
You can also do it with other strings with %s.
*** FINISH IGNORING ***
I tought you didn't know about sprintf. My bad, sorry, I mistook the situation.

Anyways for security reasons you should use snprintf, but as far as you do it "for yourself" it should give no big harm.

Anyways, a Constructor is a Piece of Code in a Class that gets executed when you declare one. Want a example? Here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Example {
public:
    Example() // Constructor
    {
        printf("Hello, I'm Example!\n");
    }
    ~Example() // Destructor, will be called when you get out of the function
    {
        printf("Oh, GoodBye, I was the Example... :(");
        getchar();
    }
};
int main()
{
    Example ex; // This will also print "Hello, I'm Example!", because it's in the constructor!
    return 0; // The destructor will now be called because you're leaving the main function, and will print "Oh, GoodBye, I was the Example... :(".
    // Also, in the destructor i've put a getchar. This will allow the console to stay up more time (Until you press a key)
}
Last edited on
I was wrong about the sprinf, but my comment about using Row and Col was still right, one day this will save you.

Any have fun
Haha thanks, When my code is finished (and it works) ill refine it continuously to make it easier to read, like using Row and Col, thanks guys!

thanks EssGeEich for your explanation, really helped, i think im getting wierd numbers is because im modifying uninitionalized variables
Hey all again, ive tried various things, but i dont understand, i printf in one function and it comes out fine and then i do the same thing later on and it comes out with something entirely different (where the variable has not been changed).

I dont understand...
Try debugging some more. Put some breakpoints... Make Assertions...
but what are the simple ways of accessing a class variable object member, some code would be nice! :D

Class variables are static members. All the objects of that class have the same value in those variables.
1
2
3
4
class electron{
public:
  static double charge, mass;
};
To access them from outside, they must be accessible (public).
Simply prefix with the class name electron::mass

For object members, you need an object to act with. <object name[i]>.<[i]member>
1
2
defineMap map;
map.map[42]



To access members inside a method (function of the class), simply write the member name.
That's it.
If you think there is ambiguity, you may use this
So in defineMap::loadChunk() you may write
1
2
3
map[whichChunk].x = x;
this->map[whichChunk].x = x;
defineMap::map[whichChunk].x = x;
The last one is used when dealing with inheritance. Trying to execute a method of the parent class, for which redefinition may be provided.
Pages: 12