question regarding polymorphism

Hi,

I'm having an issue trying to use the print() method of a subclass that is declared in the manner

Creature& cr = grid.get(i, j);

where grid.get(i, j) returns a Creature that has been initialized as a Dragon, a subclass of creature. The Creature is stored by value in the grid. When I call the print method, however, the Creature's print() method is called, and not the Dragon's. The print() function in both is defined as virtual.

Am I missing something obvious? Do I need to provide more code or explanation?

Thank you very much
Last edited on
Check the signature of Creature and Dragon's print function. They must match exactly for polymorphism to work.

If you have something like this:

1
2
3
void Creature::print() // Creature returns a void

int Dragon::print() // Dragon returns an int  BAD 


that will be a problem. The function need to have the same return type, the same parameters, etc, etc.

EDIT:
Since it would probably help, can you post your Creature::print and Dragon::print functions?
Last edited on
They are identical. I've narrowed the problem down further. The grid stores data in a two-dimensional array. Each element is assigned as such:

1
2
3
4
5
6
7
8
9
10
Dragon d;
// default constructor

for (int i = 0; i < x; i++)		// nested for loop sets all values to dragon, just for testing
{
	for(int j = 0; j < y; j++)
	{
		type[i][j] = d;
	}
}


I see the problem. Since it's binding using value, it's not calling the right print(). So how can I bind by pointer or reference without causing all elements in the array to point to the same value?

Note: later I'm going to have all array cells set to a Creature representing an empty cell in this case.

Again, thank you for your help.
Topic archived. No new replies allowed.