Inheritance and Pointers

Hey all. Hope I did not violate any posting rules.Forgive me if I did.
I thought I had the jist of it till now.I am suppose to create a zombie game.Basically a survivor fights with zombies on a map.
The problem I have is storing the map an associating it with objects.

So this is an example map.


1
2
3
4
5
6
7
5X5
S....
.....
.....
.....
....E


Now I want to create a Piece class and store the char in my class.
I tried this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Piece ** level;

ifstream in;
			in.open(files[map -1] .c_str());
			
			in>> width;
			in >> x;
			in >> height;
			
			 level[width][height];

for(int j=0;j<width;j++)
		{
			for(int i=0;i<height;i++)
			{
				in>>c;
				level[j][i] = c; //trying to store the chars i read
			}
		}


But for some reason it does not work.Please help.Where I am going wrong
closed account (o3hC5Di1)
Hi there,

You will need to dynamically allocate the level array, please note I've altered your code a little to suggest a few style-points:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
		Piece ** level;

			ifstream in(files[map -1].c_str());
			
			in>> width >> x >> height;
			level = new Piece[width][height];

for(int j=0;j<width;j++)
		{
			for(int i=0;i<height;i++)
			{
				in>>c;
				level[j][i] = c; //trying to store the chars i read
			}
		}


Now, your array level is an array which stores type "Piece". So trying to store a char into it seems quite awkward to the compiler and it will complain about this.

If your Piece class is based on a char, make sure you provide a constructor taking a char, so you can do:

level[j][i] = Piece(c);

Hope that helps. Please do let us know if you require any further help.

All the best,
NwN
The problem is that my Piece constructor take four arguments.Piece is a base class to alot of my classes.It is the base class to all the zombies and survivors I create.I want to store the map in my piece so that I use test cases to create objects.For example

1
2
3
4
5
6
7
8
9
switch(level[j][i] type)
							{
								case 'B':
									level[j][i] = ZOMBIE //creates a Zombie class
									break;
								case '/':
									// level[j][i] = WALL; // Creates a wall
									break;
								...

This then test what type is on the map and creates the objects.
Last edited on
Topic archived. No new replies allowed.