Working with Advanced Functions 291
10
43: for (int j = 0; j< width; j++)
44: {
45: std::cout << “*”;
46: }
47: std::cout << std::endl;
48: }
49: }
50:
51: // Driver program to demonstrate overloaded functions
52: int main()
53: {
54: // initialize a rectangle to 30,5
55: Rectangle theRect(30,5);
56: std::cout << “DrawShape():” << std::endl;
57: theRect.DrawShape();
58: std::cout << “\nDrawShape(40,2):” << std::endl;
59: theRect.DrawShape(40,2);
60: return 0;
61: }
DrawShape():
******************************
******************************
******************************
******************************
******************************
DrawShape(40,2):
************************************************************
************************************************************
Listing 10.1 represents a stripped-down version of the Week in Review project
from Week 1. The test for illegal values has been taken out to save room, as have
some of the accessor functions. The main program has been stripped down to a simple
driver program, rather than a menu.
The important code, however, is on lines 13 and 14, where DrawShape()is overloaded.
The implementation for these overloaded class methods is on lines 31–49. Note that the
version of DrawShape()that takes no parameters simply calls the version that takes two
parameters, passing in the current member variables. Try very hard to avoid duplicating
code in two functions. Otherwise, keeping them in sync when changes are made to one
or the other will be difficult and error-prone.
The driver program on lines 52–61 creates a rectangle object and then calls
DrawShape(), first passing in no parameters and then passing in two unsigned short
integers.
OUTPUT
LISTING10.1 continued
ANALYSIS