Reputation: 313
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.
Upvotes: 0
Views: 708
Reputation: 1344
I think you should look into factory method pattern. This will return you pointer to your base class and you will be able to call toDec method.
Usually factory method will require you to use some switch statement but if you don't want to do this at all cost take a look at how to implement factory without using if or switches here:
https://stackoverflow.com/a/3502010/8855783
This will only work if construcor of every of derived class (from Base) needs the same arguments
Upvotes: 1