I have the abstract class Currency and several subclasses like FiatMoney or Crypto. I want to store all of objects of subclasses in one vector and in the same time have access to methods, which are only in those subclasses.
My Currency.h file looks like this:
class Currency
{
public:
virtual void to_String() = 0;
float GetAmount();
string GetShortname();
void AddAmount(float);
void RemoveAmount(float);
virtual void UpdateRatio() =0;
virtual float trade(bool, float, float, float, string) = 0;
protected:
string *name, *shortname;
float *amount, *exchange_ratio;
};
and my FiatMoney.h file:
class FiatMoney : public Currency
{
public:
FiatMoney(string, string, float, float);
~FiatMoney();
void to_String();
void UpdateRatio();
float trade(bool, float, float, float, string);
void com();
private:
};
In that class I want to have additional method of this class called com(). Finally my main function looks like this:
vector<Currency*> Wallet;
Wallet.push_back(new FiatMoney("name", "shortname", 1.0, 1.0));
Wallet[0]->com();
At this point I of course have an error, that class Currency has not member call com(). How can I avoid this?
How can I get access to the function com() which is only in object of subclass FiatMoney?
Can I have method in class FiatMoney without previously declarate it as virtual function of Currency class?
Is this proper way of storing objects of different subclasses?
You would have to type-cast a
Currency*pointer into aFiatMoney*pointer, but you can only do that when the pointer is actually pointing at a validFiatMoneyobject.When you know the
Currency*pointer is pointing at aFiatMoneyobject, you can usestatic_castat compile-time, eg:Otherwise, use
dynamic_castat runtime to test the type of object being pointed at:Technically yes, though some people would argue that is not a good design choice when dealing with polymorphic classes.
Technically yes, although
Currencyshould have a virtual destructor. You have todeletethe objects younew, and a virtual destructor will allow you to calldeleteon aCurrency*pointer to invoke derived class destructors without type-casting the pointer. And as such, you should consider storing smart pointers, likestd::unique_ptr, instead of raw pointers, so thatdeleteis called automatically for you.