A STRING WITHIN AN OBJECT

Examine the program named OBJSTRNG.CPP for our first example of an object with an embedded string. Actually, the object does not have an embedded string, it has an embedded pointer, but the two work so closely together that we can study one and understand both.

You will notice that line 7 contains a pointer to a string named line_of_text. The constructor contains an input parameter which is a pointer to a string which will be copied to the string named line_of_text within the constructor. We could have defined the variable line_of_text as an actual array in the class, then used strcpy() to copy the string into the object and everything would have worked the same, but we will leave that as an exercise for you at the end of this chapter. It should be pointed out that we are not limited to passing a single parameter to a constructor. Any number of parameters can be passed, as will be illustrated later.

You will notice that when the three boxes are declared this time, we supply a string constant as an actual parameter with each declaration which is used by the constructor to assign the string pointer some data to point to. When we call get_area() in lines 48 through 53, we get the message displayed and the area returned. It would be prudent to put these operations in separate methods since there is no apparent connection between printing the message and calculating the area, but it was written this way to illustrate that it can be done. What this really says is that it is possible to have a method that has a side effect, the message output to the monitor, and a return value, the area of the box. However, as we discussed in chapter 4 when we studied DEFAULT.CPP, the order of evaluation is sort of funny, so we broke each line into two lines.

After you understand this program, compile and execute it.