CHAPTER 8

OBJECT AND CLASS:  EVERYTHING AS AN OBJECT OF A CLASS

 

The world around us is made of objects and each object has its own characteristics as to what it does and what can be done to it. A group of similar objects can be generated from a model (blueprint) that encompasses essential characteristics such as its data and its functionality, which is known as class.  A class bundles the data, its functions, and how these two members interact with each other as well as the outside world. Introduction of class and its objects will shift the focus from Procedural Programming (with function in center) to Object Oriented Programming where security (access), extendibility (expansion), and reusability (cost) are the major concerns.  As a matter of fact, you have already dealt with class and object.  The simple cin and cout statements are objects of the iostream class.

 

 

HOW TO MAKE A CLASS 

 

Text Box: struct employee {                 
char name[20];
int age;
double salary;
void setdata(char *, int, double);
void displaydata(char*, int, double);
};


Text Box: class employee {
public:
char name[20];
int age;
double salary;
void setdata(char *, int, double);
void displaydata(char*, int, double);
};

There are two ways to make a class, one that starts with the keyword struct and one that starts with the keyword class itself.  The following examples of employee class describe the similarities and differences between when the keyword class or the keyword struct is used. Note that the only difference between struct and class in C++ is the default accessibility of the members. By default members in struct are public, whereas members in class are private. However, you may argue that to define a class it would be easier to simply use the keyword class instead of using struct as the alternative, thus eliminating much confusion. C++ has demonstrated its loyalty to C language by extending the existing struct. A C++ programmer prefers class versus struct since the default accessibility of the members of a class is private.

 


   Figure 8.1a – A class with keyword struct.                Figure 8.1b – A class equivalent to                  

   Members are public by default.                                struct in figure 8.1a