I'm using complex numbers for learning design patterns. I'm currently using an abstract class:
namespace abstract{
class complex{
public:
virtual ~complex() = 0;
virtual double re() const = 0;
// some other virtual function
};
};
namespace cartesian{
class complex : public abstract::complex{
public:
complex(){}
~complex(){}
double re() const override{return re_;};
//... other functions
private:
double re_;
double im_;
// other
};
};
namespace polar{
class complex{
/// polar complex numbers....
};
};
I want to being able to write in the main:
cartesian::complex c(1,2);
polar::complex p(3,PI);
exponential::complex q = exp(c) + p;
print(q)
The thing is that I will have to write a lot of assignment operators with forward declarations for each class. So is there a way to make all representations of the complex class the same type, and having just different constructors? Something like pimpl with different pointers for each implementation or something with templates i don't know.
There is no common design pattern for this task.
And polymorphism is for me not a design pattern. It is a integral part of the C++ language.
And of course it is clear that everything is already existing in C++. So, you know
std::complexalready. I am not sure if you know about std::literals::complex_literals . With that you can write intuitive things like:Example taken from CPP reference
You could select one representation of a complex number and then convert all other forms into it. Then you can do all operations with one data type.
The only things that you would need to integrate then are more constructors and more assignment operators. But for that it would be better to use complex-literals.
So, my recommendation. Do not use polymorphism. It is too complex and too slow for this task.
Please consider.
For educational purposes, you may of course implement your solution. For this, use custom literals or a parser . . .