Vector/Classes hierarchy issues

I have a vector which stores things of type abilities, I have a subtype from abilities called power_stab. I'm trying to use push_back(power_stab] however... Well I'm new to using class hierarchy.

I suppose the question is, how would I push_back something of type power_stab to std::vector<abilities> abilities?
Here are the relevant classes:
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
class abilities
{
public:
	int ID;
	int last_cast;
	int cooldown;
	const std::string icon;
	void cast()
	{
		return;
	};
	bool can_cast()
	{
		if(this->last_cast + this->cooldown < SDL_GetTicks())
		{
			return true;
		}
		return false;
	}
	abilities();
};

class power_stab : public abilities
{
public:
	abilities::ID = 0;
	abilities::cooldown = 5000;
	abilities::icon = "resources/abilities/power_strike.png";
	void cast()
	{
		return;
	};
	power_stab();
};

class character
{
	public:
		std::vector<abilities> abilities;
		int char_ID;
};
Last edited on
You can't.

Think a class as a box. The box contains some values. A derived class is a larger box that contains both the box of the base class and other values.

The vector stores boxes of fixed size. You can push_pack a power_stab object because power_stab IS-A abilities, but it will only make a copy of the abililties box. That is called slicing.


What you seek is polymorphism. Make the vector contain pointers like std::unique_ptr or std::shared_ptr.


PS. does the "abilities" on line 39 refer to the "abilities" or "abilities"? Even if the compiler would be okay with that, it sure looks ambiguous.
Ah alright thanks! I'll mark as solved.
Topic archived. No new replies allowed.