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

                                                                         

 

 

 

 

 

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


  

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

Figure 8.2a – A struct. Members are declared                 Figure 8.2b – A class equivalent to

private with the key word private.                                   struct in figure 8.2

 

 

 

GENERAL SYNTAX OF CLASS AND ITS OBJECT

The following illustrates the general syntax for a class declaration and how to create an object from the class.

 

Text Box: Figure 8.3 – The general syntax for a class declaration.

 

Text Box: class classname {
 
accessspecifier:  memberdata;
accessspecifier:  functionmembers();
}; 
 
classname  objectname;


 


  

 

 

 

 


 

The following program will create an object called center, which is initialized and then is displayed. Let’s note that an object encompasses its data and its functions.

 

 

 

 

 

 

 

 

 

 

Text Box: #include<iostream>
using namespace std;
class point {
public: int x;
int  y;
public: void displayxy(){cout <<"X IS = "<<x<<" Y IS = "<<y<<endl;}
};
void main(){    
point center;
center.x=5;
center.y=6;
center.displayxy();    }//MAIN
 


Text Box:       Figure 8.4a – Creation of a simple C++ class and its object.
Text Box: X IS = 5 Y IS =6
  

 

 


 

Text Box: Figure 8.4b – A simple output of program in figure 8.4a

 

                                                                                                                   

 

 

 

 

DATA MEMBERS AND MEMBER FUNCTIONS

A class consists of data (e.g. variables) known as data members that represent the attribute of class. In addition a class consists of functions (methods) known as member functions that represent the action or operation of the class. 

Text Box: #include<iostream>
using namespace std;
class point {
public: int x;
int  y;
public: void displayxy(){cout <<"X  IS = "<<x<<" Y  IS  = "<<y<<endl; }
            void movexy(int mx,int my){ x=x+mx; y=y + my;}
};
void main(){
            point corner;
corner.x=2;
corner.y=4;
corner.displayxy();
corner.movexy(10,20);
corner.displayxy();    }//MAIN
 
Text Box: Figure 8.5a – A program showing a class with its data members and member functions
Text Box: X IS = 2 Y IS = 4
X IS = 12 Y IS = 24
Text Box: Figure 8.5b – Output of the program in figure 8.5a

 

 

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

OBJECTS DO NOT MIX

For every object that is created from class it will have its own data member values and its own functions.  In the following example, data member x and y of object center are different from data members x and y of object corner

Text Box: #include<iostream>
using namespace std;
class point {
public: int x;
int  y;
public: void displayxy(){cout <<"X  IS ="<<x<<" Y  IS = "<<y<<endl; }
            void movexy(int mx,int my){ x=x+mx; y=y + my;}
};
void main(){
             point center,corner;
center.x=5;
center.y=6;
corner.x=2;
corner.y=4;
center.displayxy();
corner.displayxy();
corner.movexy(10,20);
center.movexy(100,200);
corner.displayxy();
center.displayxy();        }//MAIN
 
 
Text Box: X IS = 5 Y IS = 6
X IS = 2 Y IS = 4
X IS = 12 Y = 24
X IS = 105 Y = 206
Text Box: Figure 8.6b – Output of the program in figure 8.6a
Text Box: Figure 8.6a - A program showing more than one object created from the same class.

 

 

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

CLASS ACCESSIBILITY: INFORMATION HIDING

One idea behind the class is the access ability of its members (data and function members). A class may want to hide its information detail (implementation detail) from others by allowing only certain members (interface) to access it. There are three keywords that define the accessibility of a class: public, private and protected.

 

Text Box: class employee {
private: char name[20];
 int age;
 double salary;
public:   void setdata(char *, int, double);
  void displaydata(char*, int, double);
};
Text Box: Figure 8.7a – A simple class with the use of key word private

 

 

  

 

 

 

 

 

 

 

 

 

 


 

In the above class example since default accessibility is private there would be no need to place the keyword private before the data members. This is shown in below example.

 

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

 

 

 

 

 

 

 


 

                                                                                                

 

 

 

Text Box: Figure 8.7b – A simple class without the use of keyword private

 

 

 

 

 

 


 

WHAT SHOULD BE PRIVATE AND WHAT SHOULD BE PUBLIC?

In a class the data is usually set to private and the functions are set to public. This way data cannot be accessed directly from outside of class preventing unintentional change of data. However, from the outside class (e.g. main program) data can be accessed or changed by the member functions that are set to public.

Text Box: #include<iostream>
using namespace std;
class point {
private: int x;
 int  y;
public: void setxy(int sx, int sy){x=sx; y=sy; } 
void displayxy(){cout <<"X is "<<x<<" Y is "<<y<<endl; }
};
void main(){ 
point center;
center.setxy(5,6);
center.displayxy();     }//MAIN
 
Text Box: Figure 8.8a – A class showing private and public access to its data and function members.
 
Text Box: X is 5 Y is 6
Text Box: Figure 8.8b – Output of Figure 8.8a

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

Note that by having x and y as private, the main program cannot access the x and y directly therefore access has to be through a member function.

 

 

WHEN DO YOU MAKE A FUNCTION PRIVATE?

 

The functions of a class are known as interface, meaning user of the class (outsider) through these functions can access the class. Therefore these functions are mainly set to public. However there are situations when there is no need for an outsider to access a class function and the task of the function is to provide an inside job, therefore it is set to private.


 

 

Text Box: #include<iostream>
using namespace std;
class point {
private: int x;
int  y;
private: void resetxy(int x,int y){ x=0, y=0;}
public: void setxy(int sx, int sy){x=sx; y=sy; } 
             void displayxy(){cout << "X IS = "<<x<< " Y IS = "<<y<<endl; 
                     resetxy(x,y);}
};
void main(){    
            point center;
            center.setxy(5,6);
            center.displayxy();     }//MAIN
 

 

                                                                                                                                  

 

 

 

 

 

 

 

 

Text Box: Figure 8.9a – A program showing the use of a private member function 
 
Text Box: Figure 8.9b – Output of Figure 8.9a
Text Box: X IS = 5 Y IS = 6

 

 

 

 

 

 

 

 

 

 

 


 

In this example the function resetxy( ) is set to private and it is called from function displayxy(). Note that function resetxy( ) can not be invoked from the main program.

 

 

FROM C STRUCTURE TO C++ CLASS

 

In C language, the structure bundles only data, however, in C++ structure (class) bundles data and functions, which is the major difference between C structure and C++ structure (class).  Interestingly, the original name of C++ was “C with classes”.  One can see that a prime reason for creation of the C++ was the frustration of simulating classes in C by using structure and the use of pointer to the functions instead of inclusion of functions.

 

 

CLASS AS A USER DEFINED TYPE (DATA ABSTRACTION)

 

C/C++ has its own type such as built-in data type (int, float, char, boolean).  However, a user can make its own type as needed (class) and make the object (variable) from it. The class is the blueprint and object is the real thing that you work with.  In other words, an object is the instance of a class. For example, an analogous example for class would be a built-in type such as int x; Where int is a class and x is an object of the class int. In the following example, point is the class and center is the object of the class:

 

Text Box: #include<iostream>
using namespace std;
class point{
            int x;
            int y;
public: void setxy(int sx, int sy){ x=sx; y=sy;}
            void displayxy(){ cout <<"X IS "<<x<<" Y IS "<<y <<endl; }
            void movexy(int mx,int my){ x= x+mx ;  y=y + my; }          
};
void main(){
            point center;
            center.setxy(10,20);
            center.displayxy();
            center.movexy(5, 3);
            center.displayxy();    }//MAIN
 
Text Box: X IS 10 Y IS 20
X IS 15 Y IS 23
Text Box: Figure 8.10b – Output of Figure 8.10a
Text Box: Figure 8.10a – A program showing the use of a class object.
 

 

 

 

 

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

WHAT IS A CONSTRUCTOR?

A constructor is a special function that will be automatically invoked upon the creation of an object. The job of the constructor function is to perform the initial setup that an object needs such as the initialization of member data, opening a file, and/or memory allocation. A constructor function has the same name as class. This may be a little confusing. Unlike other functions, a constructor does not have a return value and it is not void (has only signature).  As a novice you may not find much usage for constructor, therefore your constructor may be a function with an empty body.

 

In case you don’t define a constructor, your compiler will make a default constructor for you. The following examples demonstrate a class with a simple constructor, one with no arguments and the other with arguments.

 

 


 

 

Text Box: #include<iostream>
using namespace std; 
class point {
     int x;     
     int y;
public: point() {x =0;  y = 0;} //constructor with no arguments
                        int getx()  {return x;}  
                        int gety()  {return y;}
};
void main(){   
            point center;                //center is an object
            cout<<"X IS AT "<< center.getx()<<endl; 
            cout<<"Y IS AT "<<center.gety()<<endl;     }//MAIN
 
Text Box: #include<iostream>
using namespace std;
class point {
     int  x;     
     int y;
public:      
     point(int initx, int inity) {x = initx; y = inity;} //constructor with arguments
     int getx()  {return x;}
     int gety()  {return y;}  
};
void main(){   
            point  center(5,5);        //center is an object
            cout<<"X IS AT "<< center.getx()<<endl; 
            cout<<"Y IS AT "<<center.gety()<<endl;    
}//MAIN
 
Text Box: Figure 8.11a – A program showing class constructor with no arguments.
Text Box: X IS AT 0
Y IS AT 0
Text Box: Figure 8.11b – Output of Figure 8.11a
Text Box: Figure 8.11c – A program showing class constructor with arguments.
Text Box: X IS AT 5
Y IS AT 5
Text Box: Figure 8.11d – Output of Figure 8.11c
 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

FUNCTION DEFINITION: INSIDE OR OUTSIDE OF CLASS (SCOPE RESOLUTION)

 

The body of a member function can be written either inside or outside of the class. Usually a small function of one line or two is written inside the class. In this case the compiler can treat the function as an inline function and optimize it.  For a larger function body, placing the function outside the class is preferable. When a function definition is outside of the class it is necessary to use scope resolution operator :: to associate the class with the function. For example:

 

functiontype classname:: functionname(){//function body ……..

}//end of function

Text Box: class point{
private : int x;
              int y;
public :  void setxy(int sx, int sy){x=sx; y=sy;}
              void displayxy(){cout<<”X IS = “<<x<<”Y IS = “<<y<<endl; }
};         
Text Box: Figure 8.12a – Function body defined inside the class declaration

  

 

 

 

 

 

 

 

 

 

 

Text Box: class point {
private: int x;
 int  y;
public:  void setxy(int , int ); 
 void displayxy();
};
 
void point  ::  setxy(int sx, int sy){
x=sx; y=sy; }
 
void point :: displayxy(){
cout <<”X IS “<<x<<”Y IS “<<y<<endl;}
 
 
 
 
Text Box: Figure 8.12b – Function body defined outside the class declaration

 

 

  

 

 

 

 

 

 

 

 


 

SCOPE RESOLUTION AND AMBIGUITY

Each class has its own data and function, and it is possible for different classes to have the same name for the data and function members as of the other classes. In order to resolve the ambiguity as to which member belongs to which class, a scope resolution operator :: is used.

For example:

Text Box: #include<iostream>
using namespace std;
class point{
public: int x;
int y;
point(){ x=0; y=0; }
void displayxy();      };
class coordinate {
public:  int x;
            int y;
            coordinate(){ x=0; y=0; }
            void displayxy();     };
void coordinate :: displayxy(){
     cout<<"COORDINATE x = "<<x<< " y = "<<y<<endl;
}//DISPLAYXY
void point :: displayxy(){
     cout<<"POINT x = "<<x<<" y = "<<y<<endl;
}//DISPLAYXY
void main(){
     point corner;
     coordinate center;
     corner.displayxy();
     center.displayxy(); 
     corner.x=5;
     center.x=10;
     corner.displayxy();
     center.displayxy();    }//MAIN
Text Box: Figure 8.13b – Output of Figure 8.13a
Text Box: Figure 8.13a – A program showing the use of scope resolution operator ::
Text Box: POINT x = 0 y = 0
COORDINATE x = 0 y = 0
POINT x = 5 y = 0
COORDINATE x = 10 y = 0

 

 

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

SO WHAT DOES A CLASS DO?

A class bundles (encapsulates) desired data and its applied functions into a unit. The number and type of member data and functions may vary, depending on the current use of the class, and what you expect the object do.  As a result, a class may have many different perspectives in different programs or different people. In the following example, a class is defined as a pencil with desired data and the functions. The data are model, size, price, and the functions are setmodel(), getmodel(), setsize(), getsize(), setprice() and getprice(). After the class is defined we can declare the object.

Text Box: #include <iostream>
using namespace std;
class pencil{
            int model;
            int size;
            float price;
            public: void setmodel();
                        int getmodel();
                        void setsize();
                        int getsize();
                        void setprice();
                        float getprice();   };
void pencil :: setmodel(){       cout<<"ENTER PENCIL MODEL NUMBER: ";
                                                cin>>model;}
int pencil :: getmodel(){          return model;}
void pencil :: setsize(){           cout<<"ENTER THE SIZE OF THE PENCIL: ";
                                                cin>>size;}
int pencil :: getsize(){              return size; }
void pencil :: setprice(){          cout<<"ENTER THE PRICE OF THE PENCIL: ";
                                                cin>>price;}
float pencil :: getprice(){         return price;}
void main(){
            pencil mypencil;  //The class is pencil and the object is mypencil.
            mypencil.setmodel();
            mypencil.setsize();
            mypencil.setprice();
    cout <<"MODEL OF THE PENCIL IS   "<<mypencil.getmodel()<<endl<<
                "SIZE OF THE PENCIL IS         "<<mypencil.getsize()<<endl<<
                "THE PRICE IS                          "<<mypencil.getprice()<<endl;
}//MAIN
 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

Figure 8.14a – A simple example of the use of class members.

 

 

 

 

Text Box: ENTER PENCIL MODEL NUMBER: 53489
ENTER THE SIZE OF THE PENCIL: 2
ENTER THE PRICE OF THE PENCIL: .99
MODEL OF THE PENCIL IS   53489
SIZE OF THE PENCIL IS         2
THE PRICE IS                          0.99
Text Box: Figure 8.14b – Output of Figure 8.14a

 

 

  

 

 

 

 

 

 

 

 

 

 

 

 


 
WHAT IS A CLASS DESTRUCTOR

A class destructor is a special member function that is called (invoked) automatically as an object ready to cease to exist (out of scope). The job of the destructor is to do necessary clean up for the objects that are not going to be used in the program any more. This includes release of captured resources such as files, dynamic memory allocation, or even display of a message. A destructor carries the same name as the class and the constructor except it is preceded by a tilde sign ~. Though a destructor is a function, it does not return a value and does not need a void.

 

The following program simply demonstrates how a class destructor is declared and called.

Text Box: #include <iostream>
using namespace std;
class greeting{
   public:
   ~greeting();    
};
greeting:: ~greeting(){
          cout<<"BYE! I AM THE DESTRUCTOR OF YOUR PROGRAM"<<endl;}
void main(){ 
          greeting hello;                                       
          cout <<"JUST CHECKING DESTRUCTOR...."<<endl;     }//MAIN
 
Text Box: Figure 8.15a – A simple example of class destructor
Text Box: JUST CHECKING DESTRUCTOR....
BYE! I AM THE DESTRUCTOR OF YOUR PROGRAM
Text Box: Figure 8.15b – Output of program in Figure 8.15a

 

 

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 
AUTOMATIC INVOCATION OF CONSTRUCTOR AND DESTRUCTOR

                         

Both constructors and destructors are called automatically without explicitly mentioning its name. Therefore, constructor is called when an object is created.  Destructor is called when the object ceases to exist (out of scope). The following program demonstrates the automatic calling of the constructor as the object hello is created and calling to destructor as the end of block is reached. A compiler makes its own default constructor and destructor if you do not make one.

 

Text Box: #include <iostream>
using namespace std;
class greeting{
    public:    greeting(){cout<<"HELLO! I AM THE CONSTRUCTOR  "<<endl;}
                   ~greeting(){cout<<"BYE!    I AM THE DESTRUCTOR      "<<endl;}
};
void main(){ 
    greeting  hello;        
    cout <<"JUST CHECKING CONSTRUCTOR AND DESTRUCTOR….."<<endl;
}//MAIN
Text Box: Figure 8.15c - Automatic calling of constructor and destructor.

  

 

 

 

 

 

 

 

 

 

 

 

 


 

Text Box: HELLO! I AM THE CONSTRUCTOR
JUST CHECKING CONSTRUCTOR AND DESTRUCTOR…..
BYE!    I AM THE DESTRUCTOR

 

                  

 

 

 

 

 

Text Box: Figure 8.15d – Output of the program in Figure 8.15c

 

 

 

 

 

 

 


 

SIMPLE SEARCH PROGRAM: CLASS, CONSTRUCTOR, AND DESTRUCTOR

The following search program defines an abstraction called person that contains the data that belongs to a person and a function called search, which locates the telephone number of the person in search. The class constructor is used to open the file and the class destructor is used to close the file.  For simplicity the data and function were kept small. However you may want to expand it. This program asks the user to enter a name and then the program searches the input file (data.in) for that particular name. If the name is found in the data file, the name and phone number are displayed on the screen.

 

 

 

 

 

Text Box:   #include <fstream>
  #include<iostream>
  #include <string.h>
  using namespace std;
  class person{
   private: char name[20];
                char telephone[18];
    ifstream fin;
   public:  person(){ fin.open("data.in"); }
   ~person(){fin.close(); }
   search (char []);
};
person :: search(char searchname[]){
while(fin>>name>>telephone)
if(strcmp(searchname, name) == 0){
                                    cout<<"FOUND…"<<endl;
cout<<"NAME : "<<name<<endl<<"PHONE NO : "<<telephone<<endl;
return 1;   }//IF
cout<<"NOT FOUND..."<<endl;
return 0;          }//SEARCH
void main(){
person employee;
char nametosearch[20];
cout<<"ENTER NAME TO SEARCH : ";
cin>>nametosearch;
employee.search(nametosearch);      }//MAIN
Text Box: JOHN              (516)420-9753
MARY                (212)455-1378
ADAM            (718)834-7676
Text Box: Figure 8.16a – A search program

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

                                              

 

 

 

 

Text Box: Figure 8.16b – Data file used for the search program in Figure 8.16a. It contains names and phone numbers and is called data.in
Text Box: Figure 8.16c – Output for the search program in Figure 8.16a
Text Box: ENTER NAME TO SEARCH : ADAM
FOUND...
NAME : ADAM
PHONE NO : (718)834-7676
 
ENTER NAME TO SEARCH : GLORIA
NOT FOUND...

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

BANK ACCOUNT PROGRAM

 

The following is a simple example of a bank account program that uses class and file handling. There is a menu from which you can choose to view balance, deposit, withdraw, or exit. The program is written with two classes, customerdata and bankaccount.      

           

#include <fstream>

#include<iostream>

#include <iomanip>

using namespace std;

const int bucketsize = 5;

class customerdata{

public: char name [15];

                  long int accno;

                  double accbalance;

};

class bankaccount{

private: long int searchaccno;

                   double accbalance,transactionamount;

                   int totalrecord, loc;

                   customerdata custdata[bucketsize];  

public:  ifstream fin;

                   bankaccount();

                   ~bankaccount();

                   void deposit();

                   void withdraw();

                   int searchcustomer();

                   void getcustomerid();

                   void showbalance();

};

bankaccount :: bankaccount(){    

      int i = 0;

      totalrecord = 0;

      fin.open("acc.dat");

      while(fin>>custdata[i].name>>custdata[i].accno>>custdata[i].accbalance){

                  i++;

                  totalrecord ++;  }//WHILE

      }//CONSTRUCTOR

bankaccount :: ~bankaccount(){  

      fin.close();       }//DESTRUCTOR

void bankaccount :: deposit(){    

      cout<<"ENTER THE AMOUNT OF DEPOSIT:  $";

      cin>>transactionamount;

      custdata[loc].accbalance += transactionamount;  }//DEPOSIT

void bankaccount :: withdraw(){ 

      cout<<"ENTER THE WITHDRAWAL AMOUNT:  $";

      cin>>transactionamount;

      if(transactionamount <= custdata[loc].accbalance)

                  custdata[loc].accbalance -= transactionamount;

      else cout<<"NOT ENOUGH FUNDS AVAILABLE"<<endl;        }//WITHDRAW

void bankaccount :: showbalance(){        

      cout<<"UPDATED ACCOUNT BALANCE IS:  $"<<setprecision(2)

                  <<setiosflags(ios::fixed |  ios::showpoint)<<custdata[loc].accbalance<<endl;

      }//SHOWBALANCE

int bankaccount :: searchcustomer(){       

      int i;

      for(i=0; i<totalrecord; i++)

                  if(searchaccno == custdata[i].accno){

                              loc = i;

                              return i;} //IF

      return -1;  }//SEARCHCUSTOMER

void bankaccount :: getcustomerid(){     

      cout<<"ENTER CUSTOMER ACCOUNT NO:  ";

      cin>>searchaccno;  }//GETCUSTOMERID

void main(){         

      char selection, answer = 'Y';

      bankaccount accounts;

      do{     accounts.getcustomerid();

                  if(accounts.searchcustomer() != -1){

                              do{

                                          cout<<"PLEASE SELECT YOUR CHOICE: ";

                                          cout<<"<B>alance <D>eposit  <W>ithdrawal  <E>xit ";

                                          cin>>selection;

                                          switch(selection){

                                          case 'b': case 'B': accounts.showbalance();

                                                      break;

                                          case 'd': case 'D':  accounts.deposit();

                                                      accounts.showbalance();

                                                      break;

                                          case 'w': case 'W': accounts.withdraw();

                                                      accounts.showbalance();

                                                      break;

                                          case 'e': case 'E':   cout<<"THANK YOU"<<endl;

                                                      break; 

                                          default : cout<<"INVALID CHOICE"<<endl;   }//SWITCH

                  }while(selection != 'e' && selection != 'E');

                  }//IF

                  else cout<<"INVALID ACCOUNT NUMBER"<<endl;

                               cout<<"PROCESS AGAIN <Y>es or <N>o  ";

                               cin >> answer;

      }while(answer == 'Y' || answer == 'y');

}//MAIN

Text Box: Figure 8.17a – Bank Account program
Text Box: JOHN              14367  243.00
SARAH          24543  746.00
ABRAHAM   38437  567.00
JULIA             45654  567.00

 

 

  

 

 

 

 


 

                                                                                                 

 

 

Text Box: Figure 8.17b – Data file named acc.dat
Text Box: Figure 8.17c – Sample output of the bank account program
Text Box: ENTER CUSTOMER ACCOUNT NO:  14367
PLEASE SELECT YOUR CHOICE: <B>alance <D>eposit  <W>ithdrawal  <E>xit B
UPDATED ACCOUNT BALANCE IS:  $243.00
PLEASE SELECT YOUR CHOICE: <B>alance <D>eposit  <W>ithdrawal  <E>xit D
ENTER THE AMOUNT OF DEPOSIT:  $500.00
UPDATED ACCOUNT BALANCE IS:  $743.00
PLEASE SELECT YOUR CHOICE: <B>alance <D>eposit  <W>ithdrawal  <E>xit E
THANK YOU
PROCESS AGAIN <Y>es or <N>o  N

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

RAINFALL PROGRAM WITH CLASS

The below Rainfall program is an example of a real world program, which uses classes and objects. The program displays the maximum, minimum, median, and average temperature of a particular month and the amount of rainfall.  

 

#include <iostream>

#include <fstream>

#include <iomanip>

#include <cstdlib>

using namespace std;

#define bucketsize 31

class forecast{

public: ifstream fin;

            int   totalitems;

            int   date[bucketsize];

            float temperature[bucketsize];

            float rainfall[bucketsize];

            float findaverage(float[]);

            float findsum(float []);

            float findminvalue(float []);

            float findmaxvalue(float []);

            float findmedian(float []);

            sortdata(float []);

public: forecast(); //constructor

            ~forecast(); //destructor

            void  printdata();         };

forecast::forecast(){    

totalitems = 0;

            fin.open("forecast.dat");

            while (fin>>date[totalitems]>>rainfall[totalitems]>>temperature[totalitems])

                        totalitems ++;   }//CONSTRUCTOR

forecast :: ~forecast(){           

fin.close();   }//DESTRUCTOR

float forecast :: findsum(float bucket []){     

float sum = 0;

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

                        sum = sum + bucket[i];

            return sum;  }//FINDSUM

float forecast::findaverage(float bucket[]){   

float average = 0;

            average = findsum(bucket) / totalitems;

            return average;  }//FINDAVERAGE

float forecast:: findminvalue(float bucket[]){           

float minval;

            int i = 0,j;

            if(bucket[0] == 0){

                        while(bucket[i++] == 0);

                                    minval = bucket[i-1]; }//IF

            else  minval = bucket[0];

     for (j=1; j<totalitems; j++)

            if (bucket[j] < minval && bucket[j] != 0)

                        minval = bucket[j];

     return minval;  }//FINDMINVALUE

float forecast::findmaxvalue(float bucket[]){            

float maxval= bucket[0];

            for (int i=1; i< totalitems; i++)

                        if (bucket[i] > maxval)

                                    maxval = bucket[i];

            return maxval;  }//FINDMAXVALUE

forecast:: sortdata(float bucket []){  

float hold;

            for (int i = 0; i < totalitems - 1; ++i)

                        for (int j= totalitems - 1; j > i; --j)

                                    if (bucket[j-1] > bucket[j]){   

                                    hold = bucket[j-1];

                                                bucket[j-1] = bucket[j];

                                                bucket[j] = hold;  }//IF

            return 0;  }//SORTDATA

float forecast::findmedian(float bucket[]){   

float median;

            sortdata(bucket);

            if (totalitems % 2 == 0) //if number of data items are even

                        median = (bucket[(totalitems/2) - 1] + bucket[totalitems/2])/2;

            else   median = bucket[totalitems/2]; //if number of data items are odd

return median;  }//FINDMEDIAN

void forecast:: printdata(){      

cout<< setprecision(1)<<setiosflags(ios::fixed|ios::showpoint);

            cout<<setw(40)<<"MAXIMUM TEMPERATURE FOR THE MONTH = "<<

            setw(5)<<findmaxvalue(temperature)<<" F"<<endl;

            cout<<setw(40)<<"MINIMUM TEMPERATURE FOR THE MONTH = "<<

            setw(5)<<findminvalue(temperature)<<" F"<<endl;

            cout<<setw(40)<<"MEDIAN TEMPERATURE FOR THE MONTH  = "<<

            setw(5)<<findmedian(temperature)<<" F"<<endl;

            cout<<setw(40)<<"AVERAGE TEMPERATURE FOR THE MONTH = "<<

            setw(5)<<findaverage(temperature)<<" F"<<endl<<endl;

            cout<<setw(40)<<"MAXIMUM RAINFALL FOR THE MONTH    = "<<

            setw(5)<<findmaxvalue(rainfall)<<" inches"<<endl;

            cout<<setw(40)<<"MINIMUM RAINFALL FOR THE MONTH    = "<<

            setw(5)<<findminvalue(rainfall)<<" inches"<<endl;

            cout<<setw(40)<<"MEDIAN RAINFALL FOR THE MONTH     = "<<

            setw(5)<<findmedian(rainfall)<< " inches"<<endl;

            cout<<setw(40)<<"AVERAGE RAINFALL FOR THE MONTH    = "<<

            setw(5)<<findaverage(rainfall)<<" inches"<<endl;

            cout<<setw(40)<<"TOTAL RAINFALL FOR THE MONTH      = "<<

            setw(5)<<findsum(rainfall)<<" inches"<<endl;  }//PRINTDATA

void main(){

            forecast march;

            march.printdata();    }//MAIN

Text Box: Figure 8.18a – Rainfall program

 

 

 

 

 

Text Box: Figure 8.18b –File named forecast.dat 
Text Box: 1          0          45
2          4          44
3          6          52
4          1          33
5          0          32
Text Box:     MAXIMUM TEMPERATURE FOR THE MONTH =  52.0 F
    MINIMUM TEMPERATURE FOR THE MONTH  =  32.0 F
    MEDIAN TEMPERATURE FOR THE MONTH     =  44.0 F
    AVERAGE TEMPERATURE FOR THE MONTH  =  41.2 F
 
    MAXIMUM RAINFALL FOR THE MONTH         =   6.0 inches
    MINIMUM RAINFALL FOR THE MONTH          =   1.0 inches
    MEDIAN RAINFALL FOR THE MONTH             =   1.0 inches
    AVERAGE RAINFALL FOR THE MONTH          =   2.2 inches
    TOTAL RAINFALL FOR THE MONTH                =  11.0 inches
Text Box: Figure 8.18c –Sample output of the program in Figure 8.18a

 

 

 

 

  

 

 

 

 

 

 

 

 

 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

 


 
TWO PARADIGMS: OBJECT VERSUS PROCEDURE

 

The Object-Oriented paradigm is divided into three phenomena: data abstraction, inheritance, and polymorphism.  The concept of data abstraction is achieved by implementation of a user-defined type-class. From the existing class (base class), a new class can be created (derived class or sub-class) that can inherit attributes and properties of the base class.  With polymorphism (meaning “many form”) one name conveniently can be used to represent many forms.  Different objects can use a single name to identify similar tasks but can be implemented differently. 

 

In Procedural Oriented Programming, a program is divided into several functions where each function caries its own task with the use of the data as it passes through its arguments. The program grows as the function and/or number of functions grow, however there is a separation between data and function.

 

Before writing a program, an Object Oriented Programmer needs to set a time to identify the object(s) as what data it contains and what function(s) are needed. By building a class, a programmer decides as what information should be hidden (private) and what information should be made accessible (public). This practice brings about the concept of abstraction, which minimizes the distraction and unintentional errors. Object abstraction will make programming easy, reusable, secure and extendible. 

 

 

PAYROLL PROGRAM WITH CLASS

 

This payroll program uses a payroll class; the main program creates an object of the class, called employee, and calls the printreport( ) member function to display the employee information that was retrieved from the file as well as results of calculations done in the program.

 

#include <iostream>

#include <fstream>

#include <iomanip>

using namespace std;

class payroll{

ifstream fin;

char employeeid[12];

char employeename[20];

char maritalstatus;

int  hoursworked,overtime;

double hourlyrate,overtimepay,regularpay,grosspay,taxrate,taxamount,netpay;

void calculategrosspay();

void calculatetax();

void calculatenetpay();

void printheadings();

void printdata();

public: payroll();

~payroll();

void printreport();   };

payroll::payroll(){       

fin.open("payroll.dat");  }//CONSTRUCTOR

payroll::~payroll(){    

fin.close();  }//DESTRUCTOR

void payroll:: calculategrosspay(){    

if(hoursworked  >  40){

                        overtime = hoursworked - 40;

                        regularpay = hoursworked * hourlyrate;

                        overtimepay = overtime * (hourlyrate * 1.5);

                        grosspay = regularpay + overtimepay;   }//IF

else  grosspay = hoursworked * hourlyrate;   }//CALCULATEGROSSPAY

void payroll ::calculatetax(){ 

if(grosspay >= 500)  taxrate = .30;

            else if(grosspay > 200.00)  taxrate = .20;

            else  taxrate = .10;

            if(maritalstatus == 'S' ||maritalstatus == 's')

                        taxrate = taxrate + .05;

            taxamount = grosspay * taxrate;   }//CALCULATETAX

void payroll :: calculatenetpay(){         

            netpay = grosspay - taxamount;  }//CALCULATENETPAY

void payroll::printheadings(){

            cout<<setw(45)<<"-PAYROLL REPORT-"<<endl;

            cout<<"------------------------------------------------------------------------------"<<endl;

            cout<<" NAME      ID       HW OT  RT-PAY  OT-PAY  GROSS"

                           "    TAX   NETPAY"<<endl;

cout<<"------------------------------------------------------------------------------"<<endl;

}//PRINTHEADINGS

void payroll::printdata(){       

            cout<<setprecision(2)<<setiosflags(ios::fixed | ios::showpoint);

            cout<<setw(6)<<employeename<<setw(12)<<employeeid<<setw(4)

            <<hoursworked<<setw(3)<<overtime<<setw(8)<<regularpay<<setw(8)

            <<overtimepay<<setw(8)<<grosspay<<setw(8)<<taxamount<<setw(8)

            <<netpay<<endl;   }//PRINTDATA

void payroll::printreport(){    

            int i = 0;

            printheadings();

            while(fin>>employeename>>employeeid>>maritalstatus>>hoursworked>>hourlyrate){

        calculategrosspay();

        calculatetax();

        calculatenetpay();

        printdata();

        i++;  }//WHILE

}//PRINTREPORT

void main(){

            payroll employee;

            employee.printreport();    }//MAIN

Text Box:     Figure 8.19b –File named payroll.dat 
Text Box: Garcia  097-45-5678    M        45             10.00
Mary    078-78-6754    S         60             15.50 
Ramon 078-56-5645    M        58             16.99
John     079-56-4577    S         25              6.99
Text Box: Figure 8.19c – Output of Figure 8.19a 
Text Box:                              -PAYROLL REPORT-
------------------------------------------------------------------------------
 NAME      ID            HW   OT  RT-PAY  OT-PAY  GROSS    TAX   NETPAY
------------------------------------------------------------------------------
Garcia    097-45-5678  45     5    450.00     75.00      525.00      157.50   367.50
  Mary    078-78-6754  60   20    930.00    465.00     1395.00    488.25   906.75
 Ramon                 078-56-5645  58   18    985.42    458.73     1444.15    433.25  1010.91
  John     079-56-4577  25   18    985.42    458.73     174.75      26.21    148.54
Text Box: Figure 8.19a – Payroll program using class

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

CLOSING REMARKS AND LOOKING AHEAD

The world around us is made of objects, each object having properties and attributes.  Likewise, Object Oriented Programming is designed to model the world of programming in terms of objects. An object or a group of objects are created from a blueprint known as a class where its functionality and data are listed. In Object Oriented Programming, as opposed to procedural (function) programming, the focus has shifted from function to object as what you want the object to do in the program. Each object that instantiate from its class contains (encapsulates) its own data members as well as its function members. The advantage of having OOP may not be obvious to novice programmers, but as the program starts to grow, having several different classes, each class having its own objects, interaction between classes and their objects become apparent. This chapter introduces the concept of class, but it is a vast area that can be explored.  Beside the concept of class, there two other major components of object oriented programming, inheritance and polymorphism, is discussed in later chapters.  


 

SELF-TEST TRUE / FALSE CHAPTER 8: CLASS

 

__ 1. A class is a blueprint that encompasses data and its functionality.

__ 2. There are two ways to make a class: one that starts with the keyword struct and one with class.

__ 3. By default, members of a struct are private while members of a class are public.

__ 4. Member functions represent the actions or operations of a class e.g. corner.movexy(10,20);

__ 5. Every object that is created from a class has its own data members and data functions.

__ 6. A class may want to hide its information detail by allowing only certain members to access it.

__ 7. There are three keywords that define the accessibility of a class: public, private, and unprotected.

__ 8. In a class the data members are usually set to public and the functions are set to private.

__ 9. The original name of C++ was C with Classes.

__ 10. Class is the blueprint and object is the thing; object is an instance of a class.

__ 11. Constructor is a special function that will be automatically invoked upon the destruction of the object.

__ 12. The job of the constructor is to perform the setup that an object needs.

__ 13. The body of a member function can only be placed outside of the class.

__ 14. When a function definition is outside of the class, the scope operator : : is used.

__ 15. Every class must have unique names for its data and functions.

__ 16. A destructor is a special member function that is automatically called when an object ceases to exist.

__ 17. A destructor carries the same name as the class and is preceded by the tilde (&) sign.

__ 18. The three pillars of object-oriented program are data abstraction, class, and inheritance.

__ 19. The concept of data abstraction is achieved by the implementation of user-defined types.

__ 20. From an existing base class a new class can inherit attributes and properties of the base class.

__ 21. With polymorphism (meaning “many form”) many names can be used to represent many forms.

__ 22. Different objects can use a single name to identify similar tasks but can be implemented differently.

__ 23. In procedural oriented programming, there is a separation between data and function.

__ 24. When building a class a programmer decides that either all members should be public or all private.

__ 25. In OOP, as opposed to procedural programming, the focus has shifted from object to function.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 CHAPTER 8  CLASS ASSIGNMENTS AND CASE STUDY

 

Q8a) Put the following list of object-oriented programming languages in order of the date they were created: C++, Java, Simula, Smalltalk.

 

Q8b) Write an example for a constructor and a destructor.  A constructor initializes the object and brings the object into existence and a destructor cleans up before the object is destroyed.

 

Q8c) Give some examples of different objects (names) used in your programming exercises. Note that an object is a collection of data (variable, state, value) and functions (operation, behavior, method). Informally speaking, an object is something with some behavior.

 

Q8d) Use an Employee or Bank Account program as an example to illustrate the concept of object-oriented programming. Understand that object-oriented programming is considered programming that supports class (data abstraction and encapsulation), polymorphism, and inheritance. With data abstraction, both data type and its operation are encapsulated (put together- wrapped up and hidden).

 

Q8e) The following program defines a structure called complexumber that contains the real and imaginary parts of a complex number. The functions to add and subtract two complex numbers are defined. Run the program and then write the functions to multiply and divide complex numbers.

 

#include<iostream>

using namespace std;

struct complexnumber{

            float real, imaginery; };

complexnumber add(complexnumber x, complexnumber y){

            complexnumber c;

            c.real=x.real+y.real;

            c.imaginery=x.imaginery+y.imaginery;

            return c;}

complexnumber subtract(complexnumber x, complexnumber y){

            complexnumber c;

            c.real=x.real-y.real;

            c.imaginery=x.imaginery-y.imaginery;

            return c;}

int main(){

            complexnumber a,b,c,d;

            a.real=6.0; a.imaginery=5.0;

            b.real=3.0; b.imaginery=4.0;

            c=add(a,b);

            cout<<c.real<<" "<<c.imaginery<<endl;

            d=subtract(a,b);

            cout<<d.real<<" "<<d.imaginery<<endl; return 0;}

 

Q8f) Convert the above program to its equivalent class version.  Use a constructor to initialize the object.

 

Q8g) Make a class called Account consisting of member data: customer id, name, address, telephone, and balance. The member functions are: deposit, withdraw, and get balance.

 

Q8h) Create a class called apple with data members: color, size, and taste and member functions such as setcolor( ), setsize( ), settaste( ), getcolor( ), getsize( ), and gettaste( ). Make objects such as Macintosh, RedDelicious, GrannySmith, or GoldenDelicious. As you know, a class is a blue print of an object. Would the Macintosh apple be a class (sub-class) or an object? Argue this.  

 

Q8i) Identify the data members and member functions in the array class of the following program.

       What is the task of the constructor?

       Can you make the constructor an inline function?

 

#include<iostream>

using namespace std;

class array{

            int x[10];

            int counter;

public:             array();

            void insert(int);

            int computetotal(); }; //ARRAY CLASS

array::array(){

            for(int i=0; i<10; i++)  x[i]=0;

            counter=0;       }//ARRAY DEFAULT CONSTRUCTOR

void array::insert(int n){

            x[counter]=n;

            counter++;       }//INSERT FUNCTION

int array::computetotal(){

            int t=0;

            for(int i=0; i<counter; i++){

                        t+=x[i];}//FOR

            return t;                        }//COMPUTETOTAL FUNCTION

void main(){

            array myarray;

            myarray.insert(5);

            myarray.insert(56);

            cout<<myarray.computetotal()<<endl; }//MAIN

 

Q8j) Create another object of the array class in the above program, perform several insertion operations, and display the total.

 

Q8k) In the above program, add another member function to the array class such as modify( ).

 

Q8l) Extend the above program to display the average of the numbers in the array instead of the total. Make the computetotal( ) function private and write a public computeaverage( ) function that calls the computetotal( ) function to get the total. The function computeaverage( ) uses the counter for the number of items and returns the average.

 

 

 

 

 

Q8m) Identify an overloaded constructor in the below program and explain how it works.

 

#include<iostream>

using namespace std;

class array{

            int x[10];

            int counter;

public:             array();

            array(int, int, int, int, int);

            void insert(int);

            int computetotal(); };//ARRAY CLASS

array::array(){

            for(int i=0; i<10; i++)  x[i]=0;

            counter=0;       }//ARRAY DEFAULT CONSTRUCTOR

array::array(int a, int b, int c, int d, int e){

            counter=0;

            insert(a); insert(b); insert(c); insert(d);

            insert(e);          }//ARRAY CONSTRUCTOR

void array::insert(int n){

            x[counter]=n;

            counter++;       }//INSERT FUNCTION

int array::computetotal(){

            int t=0;

            for(int i=0; i<counter; i++){

                        t+=x[i];}//FOR

            return t;                        }//COMPUTETOTAL FUNCTION

void main(){

            array myarray;

            myarray.insert(5);

            myarray.insert(56);

            cout<<myarray.computetotal()<<endl;

            array myarray2(4, 6, 8, 5, 9);

            cout<<myarray2.computetotal()<<endl;           }//MAIN

 

Q8n) The following constructor sets default values for the parameters if the values are not provided.

What is the advantage to this?

 

array::array(int a, int b=0, int c=0, int d=0, int e=0){

            counter=0;

            insert(a); insert(b); insert(c); insert(d);

            insert(e);          }//ARRAY CONSTRUCTOR

 

Q8o) Scope resolution (::) is used to distinguish between members of two different classes that share the same name. If two classes have functions with the same name, such as display, write a program to use scope resolution to resolve this ambiguity.

 

 

 

 

Q8p) Run the following program to understand how the constructor and destructor are called when the object is instantiated and when the object is about to be released.

 

#include<iostream>

using namespace std;

class hello{

public: hello(){ cout<<"Hello"<<endl;}//CONSTRUCTOR

                        ~hello(){ cout<<"Good Bye"<<endl;}//DESTRUCTOR

}; //HELLO CLASS

 

void main(){

            hello world;

}//MAIN

 

Q8q) Explain the control flow of the following program.

 

 #include<iostream>

 #include <fstream>

 #include <string.h>

using namespace std;

 

 class person{

  private: char name[20];

                char telephone[18];

    ifstream fin;

   public:  person(){ fin.open("data.in"); }

   ~person(){fin.close(); }

   search (char []);

};

person :: search(char searchname[]){

while(fin>>name>>telephone)

if(strcmp(searchname, name) == 0){

                                    cout<<"FOUND…"<<endl;

cout<<"NAME : "<<name<<endl<<"PHONE NO : "<<telephone<<endl;

return 1;   }//IF

cout<<"NOT FOUND..."<<endl;

return 0;

}//SEARCH

void main(){

person employee;

char nametosearch[20];

cout<<"ENTER NAME TO SEARCH : ";

cin>>nametosearch;

employee.search(nametosearch);

}//MAIN

 

 

 

 


 

CASE STUDY –PAYROLL SYSTEM PHASE 8: CLASS

 

In the previous phase, we used C-style structure to represent the data and included employee’s hiring date. In addition, we included the system time utility to display employee reports biweekly.  The program is becoming larger than ever. We have to rethink and set strategy.  So far our employees are hourly paid but now we want to include the salaried employees as well as employees that are consultants.

 

A) Convert the phase 4, a C style structure to C++ structure (class) by adding the member functions. Remember that the members of a C++ structure are public by default.

 

B) Convert the above C++ structures to class. Members of a class are private by default.

 

C) Add a class for salaried employees as well as consultant employees.