Hello,
I want to make something like this, but I don’t know how to do this in C++:
class Item
{
public:
int price;
};
class Ball : Item { };
Item items[1];
items[0] = Ball();
items[0].price = 100;
Thanks in advance!
Hello,
I want to make something like this, but I don’t know how to do this in C++:
class Item
{
public:
int price;
};
class Ball : Item { };
Item items[1];
items[0] = Ball();
items[0].price = 100;
Thanks in advance!
Have you tried running that?
The code is almost exactly the same.
class Item
{
public:
int price;
};
class Ball : public Item { };
// Global variable
// The default consturctor is called automatically for globals
Item items[1];
int main(void)
{
items[0].price = 100;
return 0;
}
The reason for public
:
And class
causes inheritance to be private
by default, hence it needs to be manually made public
in this case.
(Taken from this SO answer.)
Also you need to use pointers (c-style or smart ones like std::shared_ptr
or std::unique_ptr
depending on your use), with virtual methods for every things you might call as Item
, but implemented in its derived classes such as Ball
.
That’s because the size of an Item
might vary depending on the derived class.
That gives you something like that:
std::shared_ptr<Item> items[1];
A little late to the party:
But you’re right though.
(I think virtual functions work on references as well, but that wouldn’t be suitable for use in an array.)
Oh right, haha got a bit confused