![Text Box: struct employee {
char name[20];
int age;
double salary;
void setdata(char *, int, double);
void displaydata(char*, int, double);
};](chapter_8_files/image001.gif)
![Text Box: class employee {
public:
char name[20];
int age;
double salary;
void setdata(char *, int, double);
void displaydata(char*, int, double);
};](chapter_8_files/image002.gif)
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);
};](chapter_8_files/image003.gif)
![Text Box: struct employee {
private: char name[20];
int age;
double salary;
void setdata(char *, int, double);
void displaydata(char*, int, double);
};](chapter_8_files/image004.gif)
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.
![]()


![]()



![]()
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.


![]()
![]()
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);
};](chapter_8_files/image017.gif)
![]()
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);
};](chapter_8_files/image019.gif)
![]()
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.


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.
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.

![]()
![]()
![]()
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:


![]()
![]()
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.


![]()

![]()
![]()

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

![]()

![]()
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:


![]()


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

![]()
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.

![]()

![]()
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.

![]()

![]()
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](chapter_8_files/image054.gif)

![]()


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
![]()

![]()
![]()

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




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
![]()

![]()

![]()
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.