10-1

Simple Classes (without Member Functions)and Objects(sec 10-2)

Read sections 10-1 and 10-3. They are quite interesting and will provide a review and preparation for the next course.

Problem 10, the main program of Chapter 10, is to build a database about a group of contestants. (A database is a collection of related information.) For each contestant, it stores the name, age, hair color, salary, etc. You already know enough to write Program 10. The data can be stored in a collection of parallel arrays [have I defined?], one for the first name of each contestant, one for the last, one for the age, and so on. Sorting requires that you drag along the other array. This method scatters information about one contestant in many different locations. Because the pieces of data are clearly related to each other, there should be a way of storing them that indicates this connection.

There areseveral restrictions imposed by arrays.

  • All elements of an array must have the same data type. In other words, an array must consist of homogeneous data. (Above info can’t be stored in 2_D array—which we haven’t learned, anyway.)
  • The second restriction is more subtle: All elements of the array must be at the same level of organization; there is no hierarchy or structure among elements. For example, in an array called x, x[0] is not more important, more complex, or in any way more basic than x[1], x[2], or any other array element. In an organization, the hierarchy specifies who is president and who is employee. In an array, everyone is at the same level.
  • All elements of an array have the same name. They are distinguished only by the subscript.

A programmer must often think as much about how to store as how to process the data. A clever principle of organization--that is, a useful data structure--often makes the program much easier to write.

The text solves Problem 10 by using a class. We have used classes and objects. For example, cin and cout are objects of the class iostream.We discussed the string class and declared objects of that class. In this chapter, we will talk about programmer-defined classes. (This is analogous to the difference between using functions and defining our own. This is easier, though.) If we want to use a class that doesn’t exist, we write our own. (In fact, classes ultimately provide the basis for object-oriented programming, which is the main difference between C and C++.) For simplicity, we are going to define classes that contain only data items and no member functions.

A class

  • allows grouping of data values which are heterogeneous (of mixed type).
  • imposes on the various parts of the data a hierarchy or structure which reflects the relationships among these parts.
  • assigns names to its members.

We’ll see how to define a class, create objects to instantiate the class and use the objects.

The best way to convey the idea of a class is with a picture. Here is a picture of a class called address, which consists of a house number and a street name.

address

/ \

numb street

We define this classas follows:

class address {

public: Just type it. It’s wrong anyway. Tell me if I forget.

int numb;

string street;

};

A class definition does not set up any storage; it defines a template (or pattern) for variables. In a sense, a class definition defines a new data type:

The new type is classaddress.

  • It has two members, numb and street.
  • They are of different types.

Once the class has been defined, we can declare objects of that class. Technically, they are called objects of the class, or instances of the class; but in most cases they act just like variables.

address home, work;

We can combine the two:

class address {

public:

int numb;

string street;

} home, work;

This is usually not useful. The class definition usually appears before main() (so any function can use it) and the object declarations are usually inside a function.

General Syntax: class class_name {

public:

type_1 var_1;

type_2 var_2;

...

type_n var_n;

};

class_name object1, object2;

  • The word classis a keyword in C++.
  • The item identified as class_name is the name of the class. The name of the classcan be used to instantiate (declare) objects of that class.
  • The keyword public allows the data members to be accessed outside the class. Don’t think about it; just use it. It’s wrong anyway.
  • Each type can be any data type, including another class.WARNING: It cannot be the same class, else you have analogue of infinite recursion, which I haven’t defined.
  • The items var_1, var_2, ... var_n are the members of the class.
  • Note the braces and the semicolon at the end.
  • The items object1 and object2 are objects or instances of the class.They have the members specified byclass_name.

A member of anobject is accessed using the dot operator, object_name.membername

home.numb

work.street

In fact, it is legal (though perhaps not the best style) to have a simple variable with the same name as a member of a class.The program may also contain a variable named numb.

Does this remind you of accessing member functions of a class?

We use members just like simple variables: we can assign values to them and read, print, or compare these values, etc., always being careful to use the full dot notation.

Examples:

home.numb = 123;

cout < home.numb; ||123

home.street = "Main";

work.numb=2900;

cin > work.street; ||Bedford

TRACE

It is legal to copy an entire object to another object of the same class, by using a single assignment statement:

home = work; (We used to spend so much time in lab, we lived here.)

TRACE

This is equivalent to ……The members of the two objects now have the same values.

Let's define a class calledstudent.

student

/ | \

/ | \

name average grade

You try it.

class student { definition of student class

public:

string name;

double average;

char grade;

};

student s1, s2, pres; declaration of objects

Assuming that the members of the objects have been given values, we can use them as follows:

if (s1.average > 3.5)

s1.grade = 'A';

if (s1.average > s2.average)

pres = s1;

else

pres = s2;

Exercise: Print the name of the student with the highest grade. Be careful with the ASCII ordering.

LAB: Write the program.

LAB:S’pose a used car dealer needs to store information about each vehicle in the showroom. The dealer may use the class vehicle, which is shown below:

vehicle

/ / \ \

/ / \ \

/ / \ \

/ / \ \

model year price mileage

Give the definition for class vehicle, followed by the declaration of two objects, v1 and v2:

class vehicle {

public:

string model;

int year;

double price;

int mileage;

};

vehicle v1,v2;

Write code to compare the prices and print which model is cheaper:

if (v2.price < v1.price)

cout < "v2.model”;

else

cout < v1.model;

cout < “ is cheaper.” < endl;

RULE: The names in the dot notation are always the object names, not the names of the classes. You never wrote int=3. It was always the name of the variable, not the type.

More Complicated Class Definitions

The members of a class may have any type. That includes variables, arrays, and even other classes. Let’s add an array of courses toour student class.

student

/ | \ \

/ | \ \

name average grade courses[4]

(Draw the memory cells.)

class student { definition of student class

public:

string name;

double average;

char grade;

string courses[4];

};

student s1, s2, pres; declaration of objects

Write the code to elect the student with the highest average as president.

Please write the code to assign values to s1’s courses. You decide what he’s taking.

s1.courses[0]= “algebra”;

s1.courses[1]= “botany”;

s1.courses[2]= “cis”;

s1.courses[3]= “drawing”;

A class can be a member of another class, called a nested class.

student

/ | \ \\

/ | \\ \

name average grade courses[4] home

/ \

(Draw the memory cells.) numb street

class address {

public:

int numb;

string street;

};

class student { definition of student class

public:

string name;

double average;

char grade;

string courses[4];

address home;

};

student s1, s2, pres; declaration of objects

Note:You must define a class before you use it, so the inner class must be defined first. E.g….

Accessing Members of a Nested Class

Using a nested class is only slightly more complex than using a one-level class. To use a particular data item, we must identify the item by its full name, which uses the dot operator to connect all its levels. S’pose s1 moved to be closer to college. How would we change his street?

s1.home.street = “Bedford”;

Repeat RULE: The names in the dot notation are always the object names, not the names of the classes. You never wrote int=3. It was always the name of the variable, not the type.

Notes:Unlike arrays,

  • Members of a class may be of different types.
  • Even if all the members are the same type, it is easier to code using descriptive names.
  • There is a structure.

LAB:All the above for students. Assign or read in values.

Instead of the string name, define a class with members first and last. Change diagram and memory cells.

Print s1’s grade and his courses.

If s2 got a B, print the his first name, else print the street on which he lives.

This isn’t trivial: If s1 is taking CIS, write “yay”. Else write “boo”.

bool cis=false;

for(int i=0;i<4;i++)

if (s1.courses[i]==”CIS” & !cis){

cout < “Yay!” < endl;

cis=true;

}

if (!cis)

cout < “Yay!” < endl;

SEE contestant.cpp Use for lab below.

LAB: after fixing the crazy nesting, 1.if contestant has red hair, congratulate him, else tell him to dye it. 2. promote him to chairman. 3. if salary>1000, subtract 10, else add 100.