next up previous
Next: The declarative stuff Up: OO Previous: OO FAQ

A short C++/OO tutorial: (I) Polynomials

Toggle Background


We shall illustrate the concept of object orientation from a simple example borrowed from mathematics. Suppose we would like to implement something like a polynomial. In the beginning it is usually a good idea to think of what we would like to be able to do with our new object. Therefore, we start with an application of a (not yet existing) type Polynomial. Consider the following piece of code: Polynomial1.C

 1 // use the polynomial
 2 int main()  // this is the entry of the main program (called by the operating system)
 3 {
 4 Polynomial  p(4);   // create a polynomial of 4th degree
 5     p[0] = 1;   // 1*x^0
 6     p[4] = 2;   // 2*x^4
 7 
 8     cout << "p = " << p << endl;    // print it
 9     return 0;
10 }
We note: The input is freely formatted and everything behind a "//" is ignored as a comment. What does this program do?

Line by line walk through:

Line 1:
A comment
Line 2:
This subroutine is called by the operating system upon start (main program).
Line 3:
The block containing the subroutine starts here.
Line 4:
A new polynomial of degree 4 is declared and created (constructed). All coefficients will be initialized to zero.
Line 5:
The coefficient of the x0 monomial is initialized;
Line 6:
The coefficient of the x4 monomial is initialized;
Line 8:
Write the polynomial in some useful notation to the standard output stream (terminal).
Line 9:
Return 0 (success) to the operating system.
Line 10:
The block containing the subroutine ends here.

The output of this piece of code shall be:

p = 2*x^4 + 1



Subsections
next up previous
Next: The declarative stuff Up: OO Previous: OO FAQ
Michael Hanrath 2006-05-02