I am building a polynomial class and I would like to construct an object like this:
Variable x('x');
Polynomial p = 4(x^3) + 2(x^2) - 8;
I was wondering if there was a way to construct the Polynomial using a mathematical expression.
I have tried using a va_list and a "Term" class but it would be nicer if it could be done as shown above.
Yes, this is possible. But there is no language support for it. There is no equivalent in C++ for JavaScript or Python's
eval(). So it won't be so easy.One simple way to make this is to use the interpreter pattern for representing expressions. You'd then execute the expression using a "context" that stores a map for the variable values. More explanations here.
There are other approaches, but in the end, you'll have to parse the expression (if it comes as a string), create some kind of abstract syntax tree and either have a simple execution engine for the tree or some more elaborate symbolic math engine, i.e. on that could apply math rules (like distribution of factors, etc) on the expression tree.
Moreover, the classes that use such expressions as parameter must foresee the additional work by design. Typically, if using the interpreter pattern approach, your polynomial would probably be itself an interpreter with interpreter arguments.