Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
57 views

Comp 213 1 Object Oriented Programming

This document discusses object-oriented programming concepts including classes, objects, and procedural versus object-oriented approaches. It defines a class as a template that groups related data and operations, and an object as an instance of a class. It provides examples of classes like employees and windows. The document also notes that C++ supports both procedural and object-oriented programming styles.

Uploaded by

monica juma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views

Comp 213 1 Object Oriented Programming

This document discusses object-oriented programming concepts including classes, objects, and procedural versus object-oriented approaches. It defines a class as a template that groups related data and operations, and an object as an instance of a class. It provides examples of classes like employees and windows. The document also notes that C++ supports both procedural and object-oriented programming styles.

Uploaded by

monica juma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

lOMoARcPSD|14064121

COMP 213-1 Object Oriented Programming

Information system (University of Eldoret)

Studocu is not sponsored or endorsed by any college or university


Downloaded by raymax cyber (raymaxcyber@gmail.com)
lOMoARcPSD|14064121

COMP 213

CHAPTER ONE

INTRODUCTION TO CLASSES

Objectives: The objectives of this chapter are to:


 Explain the reasons as to why object oriented programming is better than the
traditional procedural programming;
 Understand the basic object oriented programming concepts including class,
object, members and data hiding; and
 Write simple object oriented programs using C++ language to implement the
above concepts.

Learning Outcomes: At the end of the chapter, the learner should be able to:
 Explain reasons as to why object oriented programming may be better than
traditional procedural programming;
 Explain the meanings of the terms class, object, members, encapsulation,
and data hiding; and
 Write simple programs using classes.

8.1: Introduction

8.1.1: For Readers Moving From C to C++ Programming


_________________________________________________________
For those who are already C programmers, you should find it very simple to begin
programming in C++.

The main difference between C and C++ (procedural) programs is in inputting and
outputting.

Whereas in C we use ‘stdio.h’ as the header file for inputting and outputting, in C++,
we use ‘iostream.h’.

Secondly, to input in C, we use the inbuilt function scanf() and pass two parameters
i.e. a string showing the data type of the variable we are inputting, and the variable’s
name. In C++, we use the stream cin>> followed by the variable to input (the
variable’s data type is not specified here).

Lastly, to output in C, we use the inbuilt function printf() and pass what we want to
output as a parameter. In C++, we simply use cout<< followed by what we want to
output.

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

The summary is as follows.

Table 1.1: Summary of differences between C and C++ (procedural) programs


C C++
Header file for stdio.h iostream.h
inputting, outputting
Inputting scanf() cin>>
Outputting printf() cout<<

Examples of statements in C and their equivalent in C++ are shown below. Here, we
have assumed that variable sum stores the sum of the variables num1 and num2.

Table 1.2: Examples of C statements and their C++ equivalents


C C++
(Assuming num1, num2, and
sum are integers)
printf(“\nMy first program”); cout<<“\nMy first program”;
printf(“%d is the sum”, sum); cout<<sum<<“ is the sum”;
printf(“\nThe sum is %d”, cout<<“\nThe sum is ”<<sum;
sum);
printf(“the sum of %d and %d cout<<“the sum of ” <<num1<<“
is %d”, num1, num2, sum); and ”<<num2<<“ is ”<<sum;

All other procedural programming features we are going to study (variables, decision
making, loops, functions, arrays, structs, and pointers) have the same basic syntax in
C as in C++.

C++ IS A SUPERSET OF C
As said at the beginning, C++ was developed as a modification of C to include object
oriented features. Thus, C++ contains all what is in C in addition to other features. In
fact, you can actually combine C++ statements with C statements in the same
program. But you must use a C++ compiler and not a C compiler since C++ is the
superset.

Example 1
The following program inputs two integers and outputs their sum and their product
using C++ and C statements.

The program
#include <iostream> // Include C++ header file
#include <stdio.h> // Include C header file
using namespace std;

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

void main()
{
int a, b, sum, product; // Declare variables
cout<<“\nInput a ”; cin>>a; // Input a using C++
printf(“\nInput b ”); scanf(“%d”, &b); // Input b using C

sum=a+b; product=a*b; // Compute sum, product


cout<<“\nSum is “<<sum; // Output sum in C++
printf(“\nProduct is %d”, product); // Output product in C
}

Example 2
_________________________________________________________
Write a program to compute the area and the perimeter of a rectangle.

Solution
We need to do the following tasks to solve the problem.
(i) Input the length, and the width - length, width
(ii) Compute area as area=length*width
(iii) Compute perimeter as perimeter=2*(length+width)
(iv) Output the area and the perimeter

The program
#include <iostream>
using namespace std;

void main()
{ double length, width, area, perimeter;
cout<<“\nInput the length and the width”;
cin>>length>>width;

area=length*width;
perimeter=2*(length+width);

cout<<“\nThe area is ”<<area<<“, while the perimeter is ”<<perimeter;


}

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

8.1.2: Procedural versus Object Oriented Approaches


_________________________________________________________
Just as was explained in the first chapter, C++ language allows for both procedural
programming style and object oriented programming style.

ABOUT PROCEDURAL PROGRAMMING


It is important first to remember the idea behind the traditional procedural
programming style. When writing programs using the procedural style, the emphasis
is on the steps that need to be followed to solve the problem. The programmer first
identifies the problem, and then lists the sequence of steps needed to solve the
problem. He then converts those steps into detailed descriptions of how the problem
is exactly solved (algorithms), which he then converts to a program’s code. Each step
is implemented as a function (or a procedure). Thus, this programming style
emphasizes on the steps (or procedures) needed to solve a problem.

All the previous chapters in this book are based on this style.

ABOUT OBJECT ORIENTED PROGRAMMING


Object oriented programming style on the other hand emphasizes on combining two
things in the same type (class);
(i) Data that can be stored concerning something (an object).
(ii) The operations that can be done on the object. These operations are however
implemented through functions, and so this style still borrows the procedural
programming technique to implement the operations.

All chapters from the current one henceforth are based on this style.

ABOUT CLASSES
Object oriented programming can be defined as a programming technique that uses
the concept of classes to combine data and operations that can be identified with
objects of their type.

A class is a concept used to group related things together by specifying the


characteristics of each including the type of data (or properties) that can be stored
for each object, as well as the operations that can be applied on each. The data is
specified using the usual variables, while the operations are implemented though
functions. The data and the functions are known as data members (or member
variables) and member functions (or methods in some programming languages e.g.
java) of the class respectively. Both are referred to as members of the class.

A class is therefore a user defined data type from which a variable of its type
(object) can be created. It can be thought of as a ‘template’ i.e. a main copy from

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

which copies/instances can be created. Classes are actually extensions of structs


feature of procedural programming to provide for more functionality.

Examples of classes
The following are examples of classes that may be identified in the respective areas
of applications.

(i) A class of employees (in a business application program)


Properties: Employee code, name, salary.
Operations: Input details, output details, and compute net salary.

(ii) A class of animals


Properties: Number of limbs, mode of movement, type of food (herbivorous, or
carnivorous).
Operations: Record details, delete details.

(iii) A class of circles (in a graphical user interface program)


Properties: Radius, area, and circumference.
Operations: Input area, compute area and circumference.

(iv) A class of windows (in a graphical user interface program)


Properties: Unique window code, color, size, location on screen, etc.
Operations: Open a window, close, minimize, restore, move, resize, etc.

ABOUT OBJECTS
An object is an instance (or occurrence) of its class. When a new object is created, it
automatically gets a copy of all the characteristics (or members) of its class.

For example, in the class of windows (above), a particular window on the screen is an
object. It has particular values of code, color, size, and location. Also, the above
operations can be applied on it i.e. it can be opened, closed, moved, etc. If we have
many windows opened on the screen, then we can store the properties specified above
for each. We can also apply the specified operations on each.

8.1.3: Other Features of Object Oriented Technology


_________________________________________________________
(i) Object oriented programming also provides for data hiding. Some members of
the class can be defined to be private i.e. unavailable from outside access
(unaccessible to other sections of the program including other classes). Those
available to outside access are known as public members. Data hiding is
important in ensuring data security especially in large scale software. Some
applications even require high level of data security e.g. business transactions
software, security software, etc.

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

(ii) Secondly, it provides for constructors that are special member functions for
initializing newly created objects. This is similar to initializing a newly declared
variable as explained in Chapter two.

(iii) It also provides for code reusing through inheritance. When we have an existing
class and we want to define a new class with similar members as the existing
class, we just make this new class inherit the existing class and so avoid
redefining common members. This makes programs shorter and eases
programmer’s work.

(iv) This programming technology also provides for polymorphism feature that
ensures that something can be used in different ways. Similar to using an
operator in different ways (e.g. * is used in C++ as the multiplication operator, in
declaring pointers, in pointer dereferencing and in code documentation), we can
have many member functions with the same name, each in a different class (but
in inheriting classes), and each doing a different task. For example we can have a
member function named draw() in a class of square (for outputting a square), in
a class of circle (for outputting a circle), etc. Thus, in inheriting class, we are
allowed to give different functions in different classes the same name. And
generally, we say that we are using the same name to implement different
functionalities of the program, and this simplifies programming.

(v) Object oriented programming also provides for files programming that allows
for storage of data permanently on secondary storge devices.

(vi) It also provides for class templates. Similar to functions templates covered in
Chapter four whereby we can pass data types to a function, we can also pass data
types of data members of a class from the calling statement (statement to declare
an object). This allows us to declare many objects from a single class whose data
members have different data types.

(vii)Lastly, it provides for operator overloading that allows the programmer to


program the use of an operator in a different way from the conventional way. For
example, we know that + operator adds only primitive types i.e. integers, floats
or double numbers. We can program + operator to add advanced types i.e.
objects.

All these seven features of object oriented programming are covered in the
succeeding chapters.

8.1.4: Advantages of Object Oriented Programming over Procedural


Programming
_________________________________________________________

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

 Object oriented technique is easier to understand since it specifies objects in the


real world situations i.e. in terms of their properties and operations. Most real
world problems (for example those in 8.1.1 above) involve consideration of data
and operations about the possible objects in an area of application.
 It ensures data privacy through the data hiding feature such that private data is
not available from outside access. This means that some data meant for a
particular program section (a class) is not available to other sections. This is
very important to some areas of applications that require high level of data
security.
 It ensures code reusability though the inheritance feature. This makes
programming easier since we can avoid redefining similar members when
defining many classes.
 It ensures that something can be used in different ways through polymorphism
feature. This also makes programming easier.
 It further simplifies programming work using the other features of class
templates, operator overloading and files programming as briefly explained in
section 8.1.2 above and in the succeeding chapters.

8.2: Implementing a Class

8.2.1: Syntax for Defining a Class


_________________________________________________________
A class is defined in C++ using the following syntax.
class name
{
private:
Private members definitions
public:
Public members definitions
};

EXAMPLE 1
To define a class named A for storing two private members x and y, and a public
member z, whereby all the members are integers, we write

class A
{
private:
int x, y;
public:
int z;
};

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

private accessibility level is the default i.e. if we don’t use either of the keywords
private or public when defining members of a class, then the defined members will
be, by default, private. For example, m and n are private in class d defined below.

class d
{
int m, n;
};

EXAMPLE 2
The details stored for a time are hours, minutes and seconds (all integers). We can
define a class for time as;

class time
{
int hours, minutes, seconds;
};

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

8.2.2: Syntax for Declaring an Object


_________________________________________________________
We can declare an object (instance of a class) anywhere outside the class using the
syntax
classname objectname;

EXAMPLE 1
Using class A in Example 1 of section 8.2.1 above, we can create objects of type A as

A a; // create an object named a of class A


A b; // create an object named b of class A

We can also use one statement to create many objects, e.g.

A a, b;

CREATING ARRAYS OF OBJECTS


We can also create an array of objects. For example, to create 20 objects of class A,
we can write

A a[20];

Thus, we have 20 objects named a[0], a[1], a[2], …, a[19].

ALTERNATIVE WAY OF CREATING OBJECTS


An alternative syntax for declaring objects is to put the objects’ names at the end of
the class’s definition but before the closing semi colon, i.e.

class A
{
private:
int x, y;
public:
int z;
}a, b;

AN OBJECT HAS A COPY OF ITS CLASS‘S MEMBERS


It’s important to note that when we create objects, each object gets a copy of its
class’s members (or characteristics). For example in the above code, we can illustrate
the memory allocation as follows.

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

Object a b
Private members xy xy
Public members z z
Illustration 1.1: Members of objects

That is, each of the newly created objects a and b gets a copy of the class’s members
i.e. x, y and z.

Thus, classes are types and objects are variables


Classes and objects are analogous to data types and variables respectively. Remember
that when we declare a variable of a particular type, we tell the compiler to allocate
enough space to store the variable depending on the specifications of its data type.
For example consider the statement

int x;

Here, we create a memory space named x for storing the range of values specified in
the definition of the integer data type i.e. whole numbers. x also takes 4 bytes as
specified in the data type.

Declaring an object of its class type similarly tells the compiler to allocate enough
memory space for storing the object (depending on its characteristics i.e. sizes of data
members and member functions).

Therefore classes are analogous to data types while objects are analogous to
variables. Classes are thus user defined data types. Structs of procedural
programming are another example of user defined data types.

We should thus not think of memory allocation for the class, since a class is just a
template for creating copies from – same as the data type from which variables are
created. Each declared object gets a copy of its class’s members, and we can then
proceed to access these members (but not the class’s members since they don’t really
exist).

Note that both declaring a variable and declaring an object have the same syntax as
shown above i.e.
Type instance;

EXAMPLE 2
We can use the class time defined in Example 2 of section 8.2.1 above to create two
objects as

10

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

time time1, time2;

Both time1 and time2 are objects of class time, and for each, we can store hours,
minutes and seconds.

8.2.3. Syntax for Accessing Members


_________________________________________________________
We can access the members of objects when outside the class using the dot (.)
operator using the syntax
object.membername;

EXAMPLE
Using class A and its objects a and b shown in section 8.2.2 above, we can assign
member z of object a value 9 as

a.z=9;

We can also input member z of object a as

cin>>a.z;

Note that we can only call the public members when outside the class. Therefore, the
following statements would be erroneous using the above class.

a.x=3; // ERROR. X of a is private


a.y=2; // ERROR. y of a is private
b.x=6; // ERROR. x of b is private
b.y=7; // ERROR. Y of b is private

A complete program with class A


#include <iostream>
using namespace std;
// define class A
class A
{
private:
int x, y;
public:
int z;
};

void main()
{

11

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

// create two objects


A a, b;

// assign public member z for each object some value


a.z=9; // assign z of a to 9
b.z=5; // assign z of b to 5

// output values of the public member z


cout<<“\nz of a is ”<<a.z;
cout<<“\nz of b is ”<<b.z;
}

ACCESSING MEMBERS OF AN ARRAY OF OBJECTS


Assume we create an array of objects of class A as follows;

A a[20];

The member z of each of the objects a[0], a[1], a[2], …, a[19] can be input as

cin>>a[0].z;
cin>>a[1].z;
cin>>a[2].z;
etc.

Or using a loop as

int c;
for (c=0; c<20; c++)
cin>>a[c].z;

POINTERS OF OBJECTS
From Chapter 7
Remember from chapter seven above that a pointer can be used to access various data
structures including variables, arrays and structs. For example to declare a pointer p
for pointing to an integer, we write

int *p;

So we declare p as of type int. We can let p point to an integer say x, as

p=&x;

We can access what p points to using *p, e.g. we can input x as

12

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

cin>>*p;

Pointing to objects
Similarly, a pointer can point to an object. In this case, we can declare a pointer p for
pointing to objects of class A above (i.e. p is of type A) as

A *p;

We can make p point to object a as

p=&a;

We can then assign z of object a value 9 as

(*p).z=9;

A complete program is shown below.

Program illustrating pointers of objects


#include <iostream>
using namespace std;
// define class A
class A
{
private:
int x, y;
public:
int z;
};

void main()
{
A a; // declare an object a of type A
A *p; // declare pointer p of type A
p=&a; // let p point to object a
(*p).z=9; // assign z of what p points to value 9

cout<<(*p).z; // output z of what p points to


}

NOTE

13

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

 A single pointer can point to different objects, but to only one at a time. For
example we could declare many objects of type A, and then have a single point
p being assigned to point to those different objects.

8.2.4: Using Member Functions


_________________________________________________________
INDIRECT ACCESS OF DATA MEMBERS
Note that in the immediate above program, we have declared a public data member z
and accessed it directly outside the class since its public. However, we usually make
data members hidden from outside access (private) and then access them indirectly
though public member functions i.e. call the function when outside the class which in
turn accesses the data member. It’s the data members that would ordinarily require
security from outside access.

Note that when accessing a member inside another member (function), we do not
require the object name since we are already inside the class.

For instance, we can modify the above program to have a function to input the data
members and another one to output their values, then just invoke the functions when
outside the class as shown below.

Program with member functions


#include <iostream>
using namespace std;
// define class A
class A
{
private:
int x, y, z;
public:
void input()
{
cout<<“\nInput the three values ”;
cin>>x>>y>>z;
}

void output()
{
cout<<“\nThe values are: ”<<x<<“ ”<<y<<“ ”<<z;
}
};

14

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

void main()
{
// create two objects
A a, b;

// input values of both objects


a.input(); b.input();

// output values of both objects


a.output(); b.output();
}

Member functions are therefore declared inside the class just like data members, and
called the same way we call data members, but depending on their return types. For
example, input() and output() above are void functions and so are called as

a.input(); b.input();
a.output(); b.output();

DEFINING MEMBERS OUTSIDE THE CLASS


Members can also be defined outside the class instead of inside the class using the
scope resolution operator ::. Here, we put the class name, followed by the resolution
operator just before the function name. This is used to show which class a function
belongs to.

We must write prototypes


In this case, we must also declare the functions (or the data members) inside the class
by writing their prototype inside the class. For example, we could modify the class in
the immediate above program as follows.

// define class A
class A
{
private:
int x, y, z;
public:
void input(); // protoype of input()
void output(); // prototype of output()
};

// defining input() outside the class


void A::input()
{

15

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

cout<<“\nInput the three values ”;


cin>>x>>y>>z;
}

// defining output() outside the class


void A::output()
{
cout<<“\nThe values are: ”<<x<<“ ”<<y<<“ ”<<z;
}

The advantage
The advantage of specifying member functions in this ways is the same advantage of
using function prototypes in procedural programming. When writing large programs,
it could be simpler to the programmer to first list the functionalities
(operations/functions) to be provided by each class, and then define the body of each
function later outside the classes.

Note the importance of specifying the class that a particular function belongs to
during outside class definition i.e. two classes could be having the same function
name, and so we must show which class a particular function belongs to.

ACCESSING MEMBER FUNCTIONS USING POINTERS


In section 8.2.3, we explained how to use a pointer to point to an object, and then
access the data members of the object using the pointer. This is the same syntax we
use to access member functions.

We could for example, modify the immediate above program to use a pointer to point
to objects a and b, so that main() is as follows.

void main()
{
A a, b; // create objects a,b of type A
A *p; // create a pointer p of type A

// input values of both objects


p=&a; (*p).input();
p=&b; (*p).input();

// output values of both objects


p=&a; (*p).output();
p=&b; (*p).output();
}

16

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

The operator ->


We have an alternative for accessing member functions using a pointer. Here, we use
the operator -> instead of the dot operator. For example, we could rewrite the
immediate above code as

void main()
{
A a, b; // create objects a,b of type A
A *p; // create a pointer p of type A

// input values of both objects


p=&a; p->input();
p=&b; p->input();

// output values of both objects


p=&a; p->output();
p=&b; p->output();
}

8.3: Solved Problems

8.3.1: Problem 1
_________________________________________________________
The details stored for a time are hours, minutes and seconds. The operations
performed on any time are inputting the time, displaying the time, and incrementing
the time by one second. Define a class for this.

Solution
// class definition
class time
{
// data members
int hours, minutes, seconds;
public:
void input(); // input time
void output(); // output time
void increment(); // increment time
};

void time::input()
{
cout<<“\nInput the time: hours, minutes, seconds”;

17

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

cin>>hours>>minutes>>seconds;
}

void time::output()
{
cout<<“\nThe time is ”<<hours<<“hours, ”;
cout<<minutes<<“ minutes, and ”<<seconds<<“ seconds.”;
}

void time::increment()
{ // increment in modulo of 60
seconds++;
if (seconds==60)
{
minutes++;
seconds=0;
if (minutes==60)
{
hours++; minutes=0;
}
}
}

8.3.2: Problem 2
_________________________________________________________
The details that are stored for a circle are its radius, area and circumference. The
operations performed on any circle are inputting its radius, computing its area and
circumference, and outputting the area and the circumference. Write a program to
implement this.

Solution
#include <iostream>
using namespace std;
#define pi 3.14 // define constant pi=3.14

// class definition
class circle
{
// declare data members
private:
double radius, area, circumference;

// declare member functions


public:
18

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

void input_radius();
void compute();
void output();
};

// define member functions


void circle::input_radius()
{
cout<<“\nInput the radius ”;
cin>>radius;
}

void circle::compute()
{
area=radius*radius*pi;
circumference=2*pi*radius;
}

void circle::output()
{
cout<<“\nArea: ”<<area;
cout<<“\nCircumference: ”<<circumference;
}

void main()
{
// create three objects
circle a, b, c;

// input for each


a.input_radius();
b.input_radius();
c.input_radius();

// compute for each


a.compute(); b.compute(); c.compute();

// output for each


a.output(); b.output(); c.output();
}

8.3.3: Problem 3
_________________________________________________________

19

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

The details that are stored concerning a line on the screen are the lines coordinates,
and the line’s length. The operations done on any line are getting the details of the
line (receiving the details as parameters), and plotting the line. Write a program that
uses a class of lines to implement this. The program should plot five lines.

NB: The origin is usually taken to be the top left corner of the screen. However, to
ease programming, consider the current cursor position as the origin.

Solution
#include <iostream>
using namespace std;

class lines // A class for lines


{
int x, y, length;
public:
void get_values(int, int, int);
void plot();
};

// Member function to get line values


void lines::get_values(int a, int b, int c)
{
x=a;y=b; length=c;
}

// Member function to output the line


void lines::plot()
{
int cx, cy, cline;
// leave y lines
for (cy=0; cy<y; cy++)
cout<<“\n”;

// leave x spaces before outputting


for (cx=0; cx<x; cx++)
cout<<“ ”;

//output the line


for (cline=0;cline<length; cline++)
cout<<“-”;
cout<<“\n”;
}

20

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

// main function
void main()
{
// Declare array instance of 5 lines
const int number=5;
lines line[number];
int c, x, y, length;

// For each line, get values and plot


for (c=0;c<number;c++)
{
cout<<“nInput x coordinate: ”; cin>>x;
cout<<“\nInput y coordinate: ”; cin>>y;
cout<<“\nInput the length: ”; cin>>length;

line[c].get_values(x, y, length);
line[c].plot();
}
}

8.3.4: Problem 4
_________________________________________________________
The details stored for an account include the account’s number and credit. The
operations performed on an account include opening a new account, depositing into
the account (affect the credit), and withdrawing from the account (affect the credit).
Write a program that uses a class of accounts to solve this problem.

Solution
/* Program to have deposits and withdrawals */
#include <iostream>
using namespace std;

// constant for maximum number of accounts - 50


#define maximum_accounts 50

class accounts
{
long number; // account number
double credit; // account credit
public:
// prototypes
void input_details(); // to input account details

21

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

void show_details(); // to show account details


long get_number(); // to return account number
double get_credit(); // to return account credit
void deposit(double); // to deposit to an account
void withdraw(double); // to withdraw
};

void accounts::input_details()
{
cout<<“\nInput the new account number ”; cin>>number;
cout<<“\nInput account opening credit”; cin>>credit;
}

void accounts::show_details()
{
cout<<“\nAccount number: ”<<number<<“, Credit: ”<<credit;
}

long accounts::get_number()
{ return(number); }

double accounts::get_credit()
{ return(credit); }

void accounts::deposit(double a)
{ credit+=a; }

void accounts::withdraw(double a)
{ credit-=a; }

void main()
{
accounts account[maximum_accounts];
int count=0; // counter for accounts
int number, c;
double amount;
char choice=‘1’;
// repeating operations
while (choice==‘1’ || choice==‘2’ || choice==‘3’ || choice==‘4’)
{
// show menu
cout<<“\nInput 1 to record a new account”;
cout<<“\n 2 to deposit”;
cout<<“\n 3 to withdraw”;
22

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

cout<<“\n 4 To display an account's details”;


cout<<“\n or other value to exit”; cin>>choice;

// select operation to do
switch (choice)
{
case ‘1’: // opening new account --------
account[count].input_details(); count++;
cout<<“\nAccount added.\n”;
break;

case ‘2’: // depositing some amount -----


cout<<“\nInput the account number ”;
cin>>number;
cout<<“nInput the amount to deposit ”;
cin>>amount;

// search for account number


c=0;
while (account[c].get_number()!=number &&
c<count)
c++;

// if number not found, show message


if (c==count)
cout<<“\nAccount not found”;
else // else deposit
account[c].deposit(amount);
cout<<“nTransaction complete.\n”; break;

case ‘3’: // withdrawing some amount ----


cout<<“nInput the account number ”;
cin>>number;
cout<<“\nInput the amount to withdraw ”;
cin>>amount;
// search for account
c=0;
while (account[c].get_number()!=number &&
c<count)
c++;

// if number not found, show message


if (c==count)
cout<<“\nAccount not found”;
23

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

else // else withdraw if credit is enough


if (account[c].get_credit()>=amount)
account[c].withdraw(amount);
else // else give message
cout<<“\nSorry. You don’t have
enough credit”;
cout<<“\nTransaction complete.\n”; break;

case ‘4’: // displaying account ----------


cout<<“\nInput the account number ”;
cin>>number;

// search for account


c=0;
while (account[c].get_number()!=number &&
c<count)
c++;

// if number not found, show message


if (c==count)
cout<<“\nAccount not found”;
else // else deposit
account[c].show_details();
cout<<“\n”; break;
};
}
}

8.4: More on Classes

8.4.1: Static Data Members


_________________________________________________________
MEANING OF STATIC DATA MEMBERS
Remember from above that each object gets a copy of its class’s members. Consider
the class m below as an example.

class m
{
int x;
};

Every object of class m will have its own copy of the variable x that can take any
integer value.

24

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

A static data member on the other hand is a data member that is common to the
class i.e. it’s shared by all the objects of the class. So there is only one copy of the
member created when we declare as many objects of the class as possible.

Static data members are used to store values that are common to the entire class, for
example, as a counter of the number of objects created.

PROPERTIES OF A STATIC DATA MEMBER


 It is initialized to zero when the first object of its class is created. No other
initialization is allowed (though, while defining the variable, some initial value
can be assigned to it). This is illustrated in Example 1 below whereby count is
initialized to zero when object a is created, but is not initialized again when
objects b and c are created.
 All objects of the class share the member, regardless of how many objects are
created. Thus, we have only one copy of this member created for the class.
 It exists as long as the program is running.
 It is declared starting with the keyword static as shown in Example 1 below.
 The member must be defined outside the class (using the scope resolution
operator) as shown in Example 1 below. This is important since the members
are stored separately rather than as part of the class.
 The static data member is also known as a class variable because it belongs to
the class rather than to individual objects.

EXAMPLE 1
Consider the following program.

A program with a static data member


#include <iostream>
using namespace std;

// define class A
class A
{ // declare static data member count
static int count;
public:
// increment count
void increment()
{ count++; }

// output count
void output()
{ cout<<“\ncount= ”<<count; }

25

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

};
int A::count; // define count

void main()
{ A a; a.increment(); a.output();
A b; b.increment(); b.output();
A c; c.increment(); c.output();
}

Discussion
When the program is run, the output is
count=1
count=2
count=3

The first time an object of class A is created (object a), count is initialized to zero.
We then increment count to be 1. When objects b is created, count is not initialized
to zero because of the first property above. We then increment count, so its value is
now 2. This is similar for object c.

So, every time the value of the static data member count is incremented by one
(irrespective of which object has called increment()), the new value is the old value
plus one. Thus, count behaves as a common member to the class.

Note the output that we would however get if count was a normal data member – the
output will always be value 1 (assuming the member is initialized to zero during
creation of the object) as shown in the program below.

EXAMPLE 2
We rewrite program in Example 1 above such that count is not static.

A program where count is not static


#include <iostream>
using namespace std;

// define class A
class A
{
int count; // declare a data member count
public:
/* initialize count to 0 when object is created (using a special member
function known as a constructor) */
A()

26

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

{ count=0;}

// increment count
void increment()
{ count++; }

// output count
void output()
{ cout<<“\ncount=”<<count; }
};

void main()
{
A a; a.increment(); a.output();
A b; b.increment(); b.output();
A c; c.increment(); c.output();
}

Discussion
When the program is run, the output is
count=1
count=1
count=1

In this case, since count is not static, each created object has its own copy of count,
such that when increment() is called by the object, it increments count for that object
to 1.

8.4.2: Static Member Functions


_________________________________________________________
We can also have static member functions in addition to static data members. These
are mainly used for the purpose of accessing other static members (functions or
variables) in the same class.

A static member function can be called using the class name instead of object name as
class_name::function_name;

EXAMPLE
We can modify the above program that has a static member count so that we have
static functions increment() and output() as shown below.

#include <iostream>
using namespace std;

27

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

// define class A
class A
{ // declare static data member count
static int count;
public:
// static function to increment count
static void increment()
{ count++; }

// static function to output count


static void output()
{
cout<<“\ncount=”<<count;
}
};

int A::count;

void main()
{
A a; A::increment(); A::output();
A b; A::increment(); A::output();
A c; A::increment(); A::output();
}

8.4.3. Passing Objects as Arguments and Returning Objects


_________________________________________________________
Like other arguments, an object may be passed as a function argument. It may also be
returned as a parameter (using either pass by value method or pass by reference
method – refer to Chapter four).

EXAMPLE 1
The following program declares three times (time1, time2 and time3) of class time,
and assigns values of time3 the sum of time1 and time2. It uses the member function
sum() that receives two times (objects), gets their sum and assigns this sum to the
current (calling) object.

#include <iostream>
using namespace std;

class time
{

28

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

// declare data members


int hours, minutes;

public:
// declare prototypes of member functions
void get_time(int, int);
void sum(time, time);
int get_hours();
int get_minutes();
};

// function to receive times


void time::get_time(int h, int m)
{ hours=h;minutes=m; }

/* function to assign the current time the sum of the first time and the second
time */
void time::sum(time t1, time t2)
{
minutes=t1.minutes+t2.minutes;
hours=minutes/60;
minutes=minutes%60;
hours=hours+t1.hours+t2.hours;
}

// function to return hours


int time::get_hours()
{
return(hours);
}

// function to return minutes


int time::get_minutes()
{
return(minutes);
}

void main()
{
time time1, time2, time3; /* declare three times */
time1.get_time(2, 45); /* assign values of time1 */
time2.get_time(3, 30); /* assign values of time2 */

29

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

time3.sum(time1, time2); /* time3 is sum of time1, time2 */

// output all three times


cout<<“\ntime1 hours:”<<time1.get_hours()<<“,
minutes:”<<time1.get_minutes();
cout<<“\ntime2 hours:”<<time2.get_hours()<<“,
minutes:”<<time2.get_minutes();
cout<<“\ntime3 hours:”<<time3.get_hours()<<“,
minutes:”<<time3.get_minutes();
}

When the program is run, the output is


Time1 hours:2, minutes: 45
Time2 hours:3, minutes: 30
Time3 hours:6, minutes: 15

EXAMPLE 2
We can modify above program so that the member function sum() returns a time
(object) instead of doing assignment of the total time to the calling object.

To do this, we define sum() as follows.

/* function to return a new time (object) which is the sum of the two times
passed as parameters */
time time::sum(time t1, time t2)
{
time t3;
t3.minutes=t1.minutes+t2.minutes;
t3.hours=t3.minutes/60;
t3.minutes=t3.minutes%60;
t3.hours=t3.hours+t1.hours+t2.hours;
return(t3);
}

Also, the prototype of sum() changes to


time sum(time, time);

We then call sum() as follows


time3=time3.sum(time1, time2); /* let time3 be time1 + time 2 */

The complete program


#include <iostream>
using namespace std;

30

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

class time
{
// declare data members
int hours, minutes;

public:
// declare prototypes of member functions
void get_time(int, int);
time sum(time, time);
int get_hours();
int get_minutes();
};

// function to receive times


void time::get_time(int h, int m)
{ hours=h;minutes=m; }

/* function to assign the current time the sum of the first time and the second
time */
time time::sum(time t1, time t2)
{
time t3;
t3.minutes=t1.minutes+t2.minutes;
t3.hours=t3.minutes/60;
t3.minutes=t3.minutes%60;
t3.hours=t3.hours+t1.hours+t2.hours;
return(t3);
}

// function to return hours


int time::get_hours()
{
return(hours);
}

// function to return minutes


int time::get_minutes()
{
return(minutes);
}

void main()

31

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

{
// declare three times
time time1, time2, time3;
// assign values of time1
time1.get_time(2, 45);
// assign values of time2
time2.get_time(3, 30);
// let time3 = time1+time2
time3=time3.sum(time1, time2);

// output all three times


cout<<“\ntime1 hours:”<<time1.get_hours()<<“,
minutes:”<<time1.get_minutes();
cout<<“\ntime2 hours:”<<time2.get_hours()<<“,
minutes:”<<time2.get_minutes();
cout<<“\ntime3 hours:”<<time3.get_hours()<<“,
minutes:”<<time3.get_minutes();
}

THE this OPERATOR


Consider function sum() in Example 1 above written again below.

/* function to assign the current time the sum of the first time and the second
time */
void time::sum(time t1, time t2)
{
minutes=t1.minutes+t2.minutes;
hours=minutes/60;
minutes=minutes%60;
hours=hours+t1.hours+t2.hours;
}

Referring to times for t1 and t2


Here, we receive two times i.e. t1 and t2. Inside the function, we refer to hours and
minutes of t1 as t1.hours and t1.minutes. This is similar for t2.

Referring to times of current (i.e. calling) time


However, when referring to times of the calling time, we don’t use the object’s name,
but as hours and minutes. Just as it has been in the previous examples of this chapter,
we access members inside a member function directly without using the object’s
name. This automatically refers to the members of the calling object.

32

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

We can however decide to refer to the calling object inside a member function as
below.

Using the this pointer


There exists a pointer with the name this that will always be pointing to the current
(or the calling) object. For example, we can alternatively refer to the times of the
calling object in the above example as (*this).hours and (*this).minutes. Thus, the
function sum() could have been written as

void time::sum(time t1, time t2)


{
(*this).minutes=t1.minutes+t2.minutes;
(*this).hours=(*this).minutes/60;
(*this).minutes=(*this).minutes%60;
(*this).hours=(*this).hours+t1.hours+t2.hours;
}

EXAMPLE 3
Consider class A with one data member x and a function input() that inputs x as
shown below.

class A
{ int x;
public:
void input() { cin>>x; }
};

Assume we want to modify the class to add a function larger() that receives an object
and returns the object with the largest value of x i.e. either the current object or the
received object. We can write larger as

A larger(A a)
{
if (a.x>x)
return (a);
else return (*this);
}

We can create two objects and invoke larger() as

A m, n;
m.input(); n.input();

/* Create object k, and assign it the largest of m, n*/


33

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

A k;
k=m.larger(n);

Here, the statement k=m.larger(n); calls the member function larger() using object
m and passes object n. The function returns either the received object (i.e. n) or the
current object (object m referred to inside the function as *this).

8.5: About Object Oriented Analysis and Design

8.5.1: Analysis and Design using Procedural Technique


_________________________________________________________
In Chapter one, we had an overview of analysis and design of programs using
procedural technique.

ANALYSIS
We saw that during analysis stage, we specify outputs, inputs, and steps (or
processes). In short, we emphasize on the processes that will transform the inputs
into the outputs of the system.

DESIGN
At the design stage, we transform the above processes into a description of the
program’s logic using either pseudo codes or flowcharts.

8.5.2: Using Object Oriented Technique


_________________________________________________________
Analysis and design of programs using object oriented programming technique also
aims at specifying and documenting the requirements of the system just like the
procedural technique, but is more advanced than in procedural technique.

This is just an overview


You should note here that analysis and design is a different subject from
programming, and this book aims at teaching programming and not analysis and
design. The two are however related and so it’s important for the learner to get some
overview of the later.

ANALYSIS
Modeling characteristics, behavior, interactions of entities
Rather than just describe the processes in a system that transform the inputs into the
appropriate outputs, using object oriented programming technique, we model the
system i.e. include also the objects that are responsible for such transformation. We
show the characteristics and behaviors of those objects. We also show the
interactions between the various objects.

34

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

Different object oriented analysis and design methodologies exist, but the object
oriented analysis stage might be basically considered to consist of the following steps.

35

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

Basic stages
(i) Specify the basic requirements of the user. This is just like in procedural analysis.
We specify the expected outputs, then inputs that are needed to obtain those
outputs, and then processes that need to be executed to transform the inputs into
the outputs.

(ii) Identify the entities responsible for the above processes. Entities represent roles
which may include human users, external hardware or other systems. We also
identify the attributes of the entities. These are the characteristics mentioned
above.

For example in a sales company, various entities include customer, salesman, etc.
Attributes of a customer might be a person’s id, name, contacts, and location.
Attributes of a salesman on the other hand might be a person’s id, name, contacts,
department and salary.

(iii) Identify the services to be offered by each entity. These services are also known
as interfaces, and represent the behavior mentioned above. Also, list the steps
involved in each service.

For example, a customer’s services may be register, place order, deliver goods,
etc.

(iv) Show the interactions between the various entities in the system.

One tool used here is Entities Relationships Diagrams. It shows the entities as
well as linkages showing how they are related with one another.

Another tool popularly used here is the Data Flow Diagrams. It shows how data
flows in the system. It shows how data originates from the entities, is
transformed by the various services in the system, and goes to other entities as
results of processing.

Yet another tool is a Use Case Diagram that shows relationships among the
entities (or actors) and use cases (actions representing the interactions of the
entities i.e. the services). An actor is usually drawn as a named stick figure, while
a use case is drawn as an ellipse.

For example, ordering by a customer is a use case representing a service. It may


have the steps of shopping catalogue and selecting items, sending your details to
salesman, and receiving goods from salesman. A use case diagram for the

36

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

ordering might then be as below.

Shop catalogue and


select items

Send your details


to salesman

Receive goods
from salesman

Illustration 1.2: Use case for ordering

DESIGN
The design stage uses the specifications of the analysis stage to produce a more
specific description of the system, similar to the design using the procedural
technique. Here, we produce a design of the various classes in the system, similar to
producing a design of the various functions in procedural technique.

This design shows;


 Various classes in the system (obtained from entities in the analysis stage).
 Characteristics of the classes i.e. the data members (obtained from attributes).
 Member functions of the classes (obtained from the services).
 Relationships of the classes i.e. inheritance (obtained from the entities
interactions).

One tool used here is the class diagrams. Using a methodology known as Unified
Modeling Language (UML), a class is represented by a rectangle divided into three
parts. The top part shows the class’s name, the middle part the data members and the
bottom part the member functions.

Example
Using the entities customer and salesman explained above in analysis stage, we
could have formed another entity (person) to store the common attributes of
customers and salesmen (i.e. id, name, contacts) during stage (iv) of showing
interactions between entities. In design stage, this is implemented through
inheritance.

We will have a class person storing (id, name, and contacts). Then the classes
customer and salesman will inherit this class and define their unique members (i.e.

37

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

location and department, salary respectively). A class diagram for this might look like
below.

person

Data: id, name, contacts

Functions: register

customer salesman

Data: location Data: department, salary

Functions: Order, deliver Functions: Pay

Illustration 1.3: Class diagram for ordering

8.6: Exercises

8.6.1: Self Review Questions


_________________________________________________________
1. (a) A class specifies _____________and _______________ that concern each
object of its type. These two are known as_______________ of the class.

(b) The ________ feature of object oriented programming ensures


code reusability while the __________ feature ensures that something
can be done in different ways.

(c) The ___________ and ____________ keywords are used to show hidden
and unhidden members of a class respectively.

(d) The statement to create an object named m of class n is


________________________________________________.

(e) The statement to call the member function named show() (a void function)
of object m is _________________________.

(f) The operator :: is used to ____________________________.

(g) The operator . is used to _____________________________.

(h) The operator : is used to _____________________________.

38

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

(i) The operator -> is used to ____________________________.

(j) Another name of static data members is _________________.

2. (a) If A is a class, then the statement below tells the compiler to


_________________________________________________.
A a[20];

(b) The code to declare a class named q with only one member z (an integer and
a private) is ___________________________.

(c) Assume you want a class named m with one private data member named
m_data (a character), and one public void member function named
m_function() that simply inputs the value of m_data.
(i) Write the class m.
(ii) The statement to create an object named n of m is ____.
(iii) The statement to call m_function for object n is ______.
(iv) The statement to create a pointer named q for pointing to objects of m is
_________________________________.
(v) The statement to let q point to n is _________________.
(vi) Two equivalent statements each of which invokes m_function for n
using q are _____________________.

(d) Using class m of part 2.(c) above,


(i) The statement to create an array instance named p of size 50 is
_________________________________________.
(ii) The code to invoke m_function for all the 50 instances is
_____________________________________________.

(e) Assume you want to modify class m above (in part 2.(c)) to include a
member named retrieve() that returns the value of m_data. This function
should also be defined outside the class.
(i) The declaration of retrieve is _____________________.
(ii) The definition of retrieve is ______________________.
(iii) The statements to declare a pointer named z of type m and have it point
to an object n of m are _____________.
(iv) The statement to invoke retrieve of n using z is ______.

3. State either True or False to each of the following statements.


(a) A class must have both private and public members.

(b) Private data members can not be accessed outside the class, but private
member functions can be.

39

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

(c) If a member is defined outside its class, then there must be a prototype of the
member inside the class definition.

(d) A member function must be declared outside its class.

(e) A static data member is common to all objects of the class no matter how
many they are.

(f) It’s mandatory for a member function to be public in its class.

(g) It’s mandatory for a data member to be private in its class.

(h) A difference between a usual member function and a static member function
is that the former is called using an object’s name while the later is called
using the class’s name.

Answers to Self Review Questions


1. (a) data operations members
(b) inheritance polymorphism
(c) private public
(d) n m;
(e) m.show();
(f) define a member outside its class
(g) access the member of an object
(h) show that members to be declared are either private of public. The operator
follows the keyword private or public
(i) access a member function using a pointer
(j) class variables

2. (a) declare an array of objects of type A of size 20. The array name is a
(b) class q
{
int z;
};
(c) (i) class m
{
char m_data;
public:
void m_function()
{ cin>>m_data; }
};
(ii) m n;
(iii) n.m_function();
(iv) m *q;
40

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

(v) q=&n;
(vi) (*q).m_function();
q->m_function();
(d) (i) m p[50];
(ii) for (int c=0; c<50; c++)
p[c].m_function();
(e) (i) char retrieve();
(ii) char m::retrieve()
{ return(m_data); }
(iii) m *z;
z=&n;
(iv) cout<<z->retrieve();

3. (a) False (b) False (c) True (d) False


(e) True (f) False (g) False (h) True

8.6.2: Exercises
_________________________________________________________
1. (a) Explain the advantages of object oriented programming over procedural
programming.

(b) Explain the meanings of the terms class, object, and member.

(c) Show the syntax of defining members of a class, creating objects, and calling
members of a class.

(d) In what way is a member function different from the conventional user
defined function?

(e) Explain the difference between a data member of a class and the
conventional variables.

2. (a) What is an array of class objects? How are arrays of class objects defined in
C++?

(b) What are static data members? Why would we want to use static data
members? Also show the syntax and rules of using static data members.

(c) (i) Describe how we pass and return objects. Use sample code.
(ii) Write a program with a class named integer which contains one integer-
type data member, and a member function to input the value of the data
member. Include a member function that receives two objects as
parameters and returns the one that is larger than the other (has a larger
value of the integer).
41

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

3. (a) Debug the following program.


#include <iostream>
using namespace std;
// define class x
class x
{
int a;
public
int b;

// define member functions


void input()
{
cout<<“\nInput a ”; cin>>a;
cout<<“\nInput a ”; cin>>a;
}

void output()
{
cout<<“\nInput a ”; cin>>a;
cout<<“\nInput a ”; cin>>a;
}

void main()
{
// create objects y and z
x y z;

// call member functions


y.input(); y.output();
x.input(); x.output();
}

(b) The following shows a class of storing details of a cube. Write a complete
program using the class. Create an array of 10 cubes, and invoke the member
functions appropriately.

class cube
{ // declare data members
double length, width, height;
42

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

public:
// prototypes
void input(); // to input the data members
double get_surface_area(); // to return the area
double get_volume(); // to return the volume
};

4. The details that concern a student are the student’s registration number, name,
course, and fee amount paid. The operations done on a student include
registering a new student, outputting a student’s details and paying fees
(increment with the existing fee).

Required: Write a program in C++ to implement this for 20 students.

5. The details that are stored for any employee are the employee’s name,
department, and salary. The operations performed on any employee are to
register a new employee, output an employee’s details, and return the employees
salary.

Required: Implement the above using object oriented programming.

6. For each item, we store the item’s code, name, price and quantity in stock. The
operations we can perform on any item include registering a new item,
purchasing an item (modify stock appropriately), and selling an item (input
quantity bought).

Required: Implement this using object oriented programming. Create an array of


many items, and have a menu for the user to select the operation that he wants.

7. We can store the following details for each rectangle on the screen: the
rectangle’s length, width, the location on the screen (x and y coordinates – based
on the origin (top left corner of the screen)), and the fill-character of the
rectangle. Each rectangle can be drawn, cleared, or moved (by x and y values).

Required: Write a program using a class of rectangle to do the above using only
one rectangle.

Hints
 Use a menu in the main function.
 You need to get a C++ statement that clears the screen. To clear a rectangle,
you just need to clear the screen.
 To output a rectangle, you need to clear the screen and then output it based
on its location and size.

43

Downloaded by raymax cyber (raymaxcyber@gmail.com)


lOMoARcPSD|14064121

 To move a rectangle by some values of x and y, we compute the resulting


starting coordinates of the rectangle (its top left corner coordinates), clear
the screen and then draw the rectangle at the new location.

8. Modify exercise 7 above such that you can output many rectangles on the screen.

Hint
 To clear one rectangle, you need to clear the screen, and then redraw the
existing rectangles except the one to clear.

44

Downloaded by raymax cyber (raymaxcyber@gmail.com)

You might also like