I'm writing a project in C++, and I am stuck on a problem I don't know how to handle.
I have the following classes:
1 2 3 4 5 6 7
class entity
{
friendclass item;
public:
void show_potions();
vector<item> potions;
1 2 3 4 5 6
class item{
friendclass entity;
public:
virtualvoid print_details(){}
1 2 3 4 5 6 7
class health_potion : public item{
public:
void print_details(){
cout << name << ": restores 50 hit points" << endl;}
protected:
int health_restore;
};
Please note that the constructors and other contents of the classes are irrelevant I think and I omitted them on purpose.
Somewhere in the program I have a function that generates random objects of the Item class, and puts them in the corresponding vector. I'm trying to test if it works. So I have tried to create a function in the Entity class, that would do this.
1 2 3 4 5 6
void entity::show_potions(){
vector<item>::iterator i;
for (i = potions.begin(); i != potions.end(); ++i)
i->print_details();
};
The program won't compile. The error goes as follows:
1 2 3 4 5
C:\Users\Wojtek\Desktop\PO2 - Projekt\project v. 2.0.cpp: In member function `void entity::show_potions()':
C:\Users\Wojtek\Desktop\PO2 - Projekt\project v. 2.0.cpp:90: error: invalid use of undefined type `struct item'
C:\Users\Wojtek\Desktop\PO2 - Projekt\project v. 2.0.cpp:15: error: forward declaration of `struct item'
I've only recently learned about vector, inheritance and friend classes. As can be seen, I still have problems with it.
You can't use a solid type in a vector if you want polymorphism.
Instead of:
vector<item> potions;
Use a pointer:
vector<item *> potions;
This is better though:
vector<std::unique_ptr<item>> potions;
You have to use a pointer because otherwise the vector does not know how much memory to allocate for each item - different classes use different memory, it is impossible without using a pointer.
void entity::show_potions(){
vector<item *>::iterator i;
for (i = potions.begin(); i != potions.end(); ++i)
i->print_details();
};
Good news is, I'm not getting that error anymore. Bad news is, I'm getting another one.
1 2 3 4 5
C:\Users\Wojtek\Desktop\PO2 - Projekt\project v. 2.0.cpp: In member function `void entity::show_potions()':
C:\Users\Wojtek\Desktop\PO2 - Projekt\project v. 2.0.cpp:90: error: `print_details' has not been declared
C:\Users\Wojtek\Desktop\PO2 - Projekt\project v. 2.0.cpp:90: error: request for member of non-aggregate type before '(' token