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.

// objstring.cpp
#include <iostream.h>

class box {
int length;
int width;
char *line_of_text;
public:
box(char *input_line); //Constructor
void set(int new_length, int new_width);
int get_area(void);
};

box::box(char *input_line) //Constructor implementation
{
length = 8;
width = 8;
line_of_text = input_line;
}

// This method will set a box size to the two input parameters
void box::set(int new_length, int new_width)
{
length = new_length;
width = new_width;
}

// This method will calculate and return the area of a box instance
int box::get_area(void)
{
cout << line_of_text << "= ";
return (length * width);
}

main()
{
box small("small box "), //Three boxes to work with
medium("medium box "),
large("large box ");

small.set(5, 7);
large.set(15, 20);

cout << "The area of the ";
cout << small.get_area() << "\n";
cout << "The area of the ";
cout << medium.get_area() << "\n";
cout << "The area of the ";
cout << large.get_area() << "\n";

}
// Result of execution
//
// The area of the small box = 35
// The area is the medium box = 64
// The area is the large box = 300

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.