next up previous
Next: Making it useful (ii) Up: A short C++/OO tutorial: Previous: The implementation

Making it useful (i)

Toggle Background


So far, our polynomial is not really useful and there is not much it has in common with a polynomial from mathematics. What is missing? Polynomials may be evaluated. So we want to say: p(3) and get a result for x = 3. How to do that? Obviously some new declarative stuff is necessary. We have to tell the compiler that a polynomial with a following bracket should be evaluated as a function: Polynomial4.C

 1 class Polynomial : public vector<double> { 
 2 public:
 3     // ...
 4     // function evaluation
 5     double operator () (double x) const;
 6     // ...
 7 };
 8 
 9 double Polynomial::operator () (double x) const
10 {
11 double  xx = 1; // temporary for powers of x
12 double  y = 0;  // will contain the result
13     for ( int i=0 ; i<=size()-1 ; ++i )
14     {
15         y += (*this)[i] * xx;   // add coefficient * x^n
16         xx *= x;    // next power
17     }
18     return y;   // return result
19 }
20 
21 int main()
22 {
23 Polynomial  p(4);
24     p[0] = 1;
25     p[4] = 2;
26 
27     cout << "p = " << p << endl;    // print it
28     cout << "p(3.4) = " << p(3.4) << endl;  // evaluate and print it
29     return 0;
30 }
Download Full Source

We printed only new lines of code with occasionally a few lines of environment to avoid any ambiguities.

Line by line walk through:

Line 5:
Declare: There is a new operator "()" taking one argument of a double returning a double (the second argument is implicit by this)
Line 9:
Implementation of the function evaluation for a polynomial.
Line 28:
Use the function evaluation.

The program will return:

p = 2*x^4 + 1
p(3.4) = 268.267



Michael Hanrath 2006-05-02