_TOWARDS A LESS OBJECT-ORIENTED VIEW OF C++_ by Harris Shiffman Example 1: When subscript are within range, the subscript operator invokes the one it inherits int& protected_array::operator[] (int x) { return (x >= 0 && x < size()) ? array::operator[] (x) : error_value; } Example 2: Defining two functions for finding the smaller of a pair of numbers int min (int a, int b) { return a < b ? a : b; } double min (double a, double b) { return a < b ? a : b; } main () { int x = min (5, 7); double y = min (3.2, 1.3); double z = min (16.3, 2); } % CC min.cc "min.cc", line 10: error: ambiguous call: min ( double , int ) "min.cc", line 10: choice of min()s: "min.cc", line 10: int min(int , int ); "min.cc", line 10: double min(double , double ); Compilation failed % Example 3: (a) Overloading of function names and basic operators like plus (+) and equals (=) make it possible for programs to treat these data types as if they were built into the language; (b) The template facility makes it possible to write general container classes which can be instantiated to hold any particular kind of value. (a) #include #include "fraction.h" #include "string.h" main () { Fraction d = .5, e(2, 3); Fraction f = d + e - 1; cout << "F is " << f << endl; // Prints "F is 1/6" String g = "Hello,", h = " there"; String i = g + h; cout << "I is " << i << endl; } // Prints "I is Hello, there" (b) #include #include "stack.h" main () { stack s1; // Create a stack of doubles for (int i = 0; i < 10; i++) s1.push (i + .5); for (i = 0; i < 5; i++) cout << s1.pop() << " " << s1 << endl; stack s2; // Create a stack of character pointers s2.push ("abc"); s2.push ("def"); s2.push ("ghi"); while (!s2.is_empty()) cout << s2.pop() << " " << s2 << endl; }