Sams Teach Yourself C in 21 Days

(singke) #1
Object-Oriented Programming Languages 633

33: { BD1
34: printf(“\n”);
35:
36: for ( yctr = 0; yctr < bottomleftY - topleftY; yctr++ )
37: {
38: printf(“*”);
39: }
40: }
41: }
42:
43: int main(int argc, char* argv[])
44: {
45: int pt_x1 = 0, pt_y1 = 0;
46: int pt_x2 = 5, pt_y2 = 5;
47: int pt_x3 = 0, pt_y3 = 0;
48: long side = 4;
49:
50: // Call the square function two different ways
51: square( pt_x1, pt_y1, pt_x2, pt_y2);
52:
53: printf(“\n\n”); //put blank lines between squares
54:
55: square( pt_x3, pt_y3, side);
56:
57: return 0;
58: }

*****
*****
*****
*****
*****

****
****
****
****
If you try to compile this listing as C, it will generate an error. If you compile it
as a C++ program, it will work. As you can see, this listing has two functions
with the same name (see lines 7 and 25). You can also see in lines 51 and 55 that the
square()function is called in two different ways. You learned earlier in this book that
this is not correct in a C program. In an object-oriented program, this is acceptable. This
is polymorphism in action. When the square function is called, the program determines
which is the appropriate one to use. With a C++ program, the programmer does not need
to worry about which is correct.

LISTINGB1.1 continued

OUTPUT

ANALYSIS

36 448201x-Bonus1 8/13/02 11:18 AM Page 633

Free download pdf