Issues with vector, inheritance, returning constructor

Hi guys,

Have a rather convoluted problem and I am not sure how to get about it. First Off I have a "Magic class" with the following function.

1
2
3
4
5
6
7
8

virtual Effect cast_spell()//in header file

Effect Magic::cast_spell(){//in cpp file
	/*Intentionally Empty*/
	return Effect(The_Monster,0);
}


The effect construtor looks like this

1
2
3
4
5
6

Effect::Effect(the_effect _effect, int the_result){// in cpp file
	set_effect(_effect);
	set_result(the_result);
}


The idea is simple, I need an object returned from each spell, a simple integer will not do

Then I have a "Healing" class derived from "Magic" class from above with the following function

1
2
3
4
5
6
7
8
9
Effect Healing::cast_spell(){//in healing cpp

	Dice roll;
	int temp=roll.make_rolls(dice,sides);

	return Effect(The_Player,temp);

}


In a player class I have the following declaration.

1
2
3

std::vector<Magic> spells;


and I load a healing spell thus

1
2
3
4
5

Healing healing("Healing",20,The_Healing,1,9);

	add_spell(healing);


using

1
2
3
4
5

void Player::add_spell(Magic &the_spell){
	spells.push_back(the_spell);
}


Don't worry about the variables, they are not important.

Now, everything works fine, except when I "cast" a healing spell by using the "cast_spell()" function shared by the Magic class and the Healing class, my "virtual" keyword is not working properly (i believe it's called late binding)and what's returned is:

1
2
3
4
5
6

Effect Magic::cast_spell(){//in cpp file
	/*Intentionally Empty*/
	return Effect(The_Monster,0);
}


Instead of:

 
Effect Healing::cast_spell();


Can someone tell me what's going on here? If possible, I would like to avoid pointers.

Thanks,

Mike

Last edited on
Object slicing.
std::vector<Magic> spells; you made a container of Magic objects, so it contains `Magic' objects

Use std::vector< smart_pointer<Magic> > spells; instead.
Can you please tell me however why what I am doing is not working properly?

Thanks,

Mike
toomanystars wrote:
Can you please tell me however why what I am doing is not working properly?


He did. Object slicing.

http://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c#274636
Thanks for the help guys. In the end I just ended up using pointers which solved the problem.

Mike
Topic archived. No new replies allowed.