I have an abstract class "Base" and derived classes such as Hexadecimal, Binary and so on... . User enters a string telling me what base he is currently using and enters the number. I need to use polymorphism (instead of control statements such as if, switch, etc...) to create the needed object or at least change that number to decimal so I can do the calculations needed with different numbers in different bases that I receive from user. I tried a lot but cannot find out how to do this. My current idea is to dynamically call "double toDec(const Base&)" function but don't think if it is the right move:
#include <iostream>
#include <string>
using namespace std;
class Base
{
public:
Base(string n, string b) : number(n), base(b) {}
virtual string whatBaseAreYou(string) = 0;
virtual double toDec(const Base&) { whatBaseAreYou(base); }
protected:
string number;
string base;
};
class Hex : public Base
{
public:
virtual double toDec(const Base&);
};
class Binary : public Base
{
public:
virtual double toDec(const Base&);
};
int main()
{
string number,base;
cin >> number >> base;
Base* b = new Base(number,base); //I know this line is compile error.. I don't know how to implement this...
}
I can determine my current number's base, but how can I dynamically create for example a Binary class during run time? I'm not even sure if I need abstract class Base... I don't know if I'm moving in the right direction here... this is a Inheritance + Polymorphism assignment that's why I need to solve it with these features.