I’m learning C++ by myself, “creating” a RPG. However, I’m stuck at point of creating a class named Item, which would be the base class for all game items (or if it was in Java, an interface). Here’s my code:
class Item {
public:
virtual const char* GetName() = 0;
};
I read something about “pure virtual” functions, which I’m using.
My Character class, where I use my Item:
class Character {
// some code...
void ConsumeItem(Item item);
}
But gcc gives me this error:
g++ -Wall -o adventure character.cpp adventure.cpp
In file included from adventure.cpp:3:0:
character.h:36:24: error: cannot declare parameter ‘item’ to be of abstract type ‘Item’
item.h:4:7: note: because the following virtual functions are pure within ‘Item’:
item.h:11:22: note: virtual const char* Item::GetName()
I’m very new to OOP in C++, as it is very different from Java. I already read some articles about abstract classes in C++, but I just can’t get it working.
Can you please tell me the right way to achieve this?
In Java, doing something like that will create a reference to an
Item, which you can then assign an instance of a concrete subclass.However in C++,
Item itemwill create an instance ofItem, which isn’t allowed sinceItemcontains a purevirtualfunction.To avoid this problem, you need to make
itema pointer or a reference, like: