// // This example demonstrates overloading of the function call operator, // aka operator() , to create quadratic functions. // // Consider functions f(x) = a x^2 + b x + c . #include class Quadratic { private: double coeff[3]; public: Quadratic() { // default -- zero function coeff[0] = coeff[1] = coeff[2] = 0; } Quadratic( double a, double b, double c ) { coeff[2] = a; // coefficients are numbered by degree of x coeff[1] = b; coeff[0] = c; } // implement evaluation of a function (aka "plugging in the x") double operator() ( double x ){ return ( coeff[2]*x*x + coeff[1]*x + coeff[0] ); } }; // run this test to be sure ... // Question: what happens on assignment of Quadratics? // E.g. Quadratic f1( 2, 6, -5 ), f2; // f2 = f1; // what is inside f2 now? int main(){ Quadratic f( 1, -2, 1) ; // construct x^2 - 2x + 1 Quadratic g( 1, 5, 6 ) ; // construct x^2 + 5x + 6 Quadratic h( 4, 0, -9) ; // construct 4x^2 - 9 cout << "For f(x) = x^2 - 2x + 1 \n"; for( double x = -5; x <= 5 ; x += 0.5 ) { cout << "f(" << x << ")= "; cout << f(x) << endl; // notice that f is NOT a function } cout << endl << endl; cout << "For g(x) = x^2 + 5x + 6 \n"; for( double x = -5; x <= 5 ; x += 0.5 ) { cout << "g(" << x << ")= "; cout << g(x) << endl; // notice that g is NOT a function } cout << endl << endl; cout << "For h(x) = 4x^2 - 9 \n"; for( double x = -5; x <= 5 ; x += 0.5 ) { cout << "h(" << x << ")= "; cout << h(x) << endl; // notice that h is NOT a function } cout << "\nDone.\n"; }