ICS2104 OOP Manual
ICS2104 OOP Manual
ICS2104 OOP Manual
OF
AGRICULTURE & TECHNOLOGY
Prerequisite
BIT 2104 Introduction to Programming and Algorithms
Course Purpose
This course is intended to highlight the abstract notion of object-oriented program-
ming and code reuse
Learning Outcomes
Upon completion of this course, you should be able to:
Instruction methodology
computers, textbooks, appropriate software
Assessment information
The module will be assessed as follows;
ii
• 20% of marks from one written CAT to be administered at JKUAT main cam-
pus or one of the approved centres
Course Textbooks
• David Flanagan, 2005, Java in a Nutshell (5th Edition), O’Reilly Press,
Reference Textbooks
• Flanagan, D. (2005). Java in a nutshell : a desktop quick reference. O’Reilly
(5th ed.).
Course Journals
• JOOP - Journal of Object-oriented Programming Publications.
Reference Journals
• Journal: ACM Computing Surveys - CSUR , vol. 43, no. 3 2011.
iii
Contents
iv
CONTENTS CONTENTS
6 Storage classes 34
6.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
6.2 Auto storage specifier . . . . . . . . . . . . . . . . . . . . . . . . . 34
6.3 The register storage class specifier . . . . . . . . . . . . . . . . . . 35
6.4 The static storage class specifier . . . . . . . . . . . . . . . . . . . 35
6.5 The extern storage class specifier . . . . . . . . . . . . . . . . . . . 36
7 Inheritance 38
7.1 Introduction to inheritance . . . . . . . . . . . . . . . . . . . . . . 38
7.2 Redefining and Overloading Member Functions of the Base Class . 41
7.3 Constructors of Derived and Base classes . . . . . . . . . . . . . . 41
7.4 Virtual Functions and Pure Virtual Functions . . . . . . . . . . . . . 41
8 Operator Overloading 45
8.1 Operator Overloading . . . . . . . . . . . . . . . . . . . . . . . . 45
8.2 Operation Overloading Function . . . . . . . . . . . . . . . . . . . 45
8.3 Overloading Binary Operators . . . . . . . . . . . . . . . . . . . . 46
8.3.1 Overloading + operator using a member function . . . . . . 46
8.3.2 Overloading + operator using a non-member function . . . . 48
8.4 Overloading Unary Operators . . . . . . . . . . . . . . . . . . . . . 50
8.4.1 Overloading pre-increment/decrement operators using mem-
ber functions . . . . . . . . . . . . . . . . . . . . . . . . . 50
8.5 Overloading pre-increment/decrement operators using a non-member
function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
8.6 Overloading post-increment/decrement operators using member func-
tions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
v
CONTENTS CONTENTS
9 Template 62
9.1 Introduction to Templates . . . . . . . . . . . . . . . . . . . . . . 62
9.2 Function Template . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
9.3 Class Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
vi
ICS 2104 Object-Oriented Programming I
LESSON 1
Introduction Object-Oriented Programs
Learning outcomes
Upon completing this topic you should be able to:
1
ICS 2104 Object-Oriented Programming I
• Object
An object is:
a) A run-time entity and it consume computer memory
b) An instance of a class.
c) An entity that has state, behavior and identity.
• Class
A class is
a) A template that is used to construct objects.
b) A collection of objects that have similar state and behavior.
c) A collection of objects of similar type.
• Inheritance
Inheritance is the ability to define new classes from already existing classes. This
is a powerful concept in programming. It facilitates development of programs that
are of high quality.
A class that is defined, created or derived from another class is referred to as a
sub-class, child class or a derived class.
2
ICS 2104 Object-Oriented Programming I
• Encapsulation
Encapsulation is:
a) enclosing state and behavior of an object.
b) putting together state and behavior of objects in single unit.
Encapsulation is implemented through the use of classes.
• Information hiding
Information hiding is prevention of state and behavior of an object from direct ac-
cess by other object. Information hiding is implemented through the use of access
specifiers that includes: private, public and protected. private, public and protected
are keywords
• Abstraction
Abstraction is the act of showing only the general properties of an object leaving
out the detailed properties. Abstration useful when designing complex programs.
A class is an example of an abstract data type(ADT)
• Message passing
Message passing is the way objects interact with one another in an object-oriented
program. Objects interact by sending messages to one another. For example, if
“person” and “window” are two objects in an object-oriented program, the “person”
object may send a message to the “window” requesting it to close.
3
ICS 2104 Object-Oriented Programming I
A message is a request for something to be done. Message passing has the following
information.
a) The name of the object that the message is being sent to
b) The name of the message
c) Information that the receiver of the message requires in order to respond to the
message.
• Polymorphism
3. Linker combine machine code produced by the compiler with machine code
from the libraries included in the program to produce an executable file.
4. The executable file is loaded into the main memory for execution. This is
done by a program referred to as loader.
Revision Questions
4
ICS 2104 Object-Oriented Programming I
5
ICS 2104 Object-Oriented Programming I
6
ICS 2104 Object-Oriented Programming I
LESSON 2
The Basics of an Object-Oriented Program Written in C++
Learning outcomes
Upon completing this topic you should be able to:
2.1. Introduction
C++ programs consists of functions and classes.
Some of these functions and classes are predefined while others are programmers’
defined.
It is advisable to use as many pre-defined classes and functions as possible in a
program.
Programs that uses pre-defined functions and classes are of better quality than those
that are made of programmers’s defined classes and functions. Pre-defined func-
tions and classes are stored in header files.
All C++ programs have main() method. This is the first method that is called by the
operating system when the program starting executing.
C++ programming language is a case sensitive language, and therefore the main()
function must be written in lower case.
7
ICS 2104 Object-Oriented Programming I
D e s c r i p t i o n : This program d e m o n s t r a t e s
t h e minimum number and t y p e
of s t a t e m e n t s necessary to
w r i t e a s i m p l e C++ p r o g r a m .
======================================== ∗ /
# i n c l u d e < i o s t r e a m . h>
void p r i n t ( void ) ;
i n t main ( v o i d )
{
print ();
return 0;
}
void p r i n t ( void ){
c o u t < <" H e l l o w o r l d " << e n d l ;
}
• Comments
8
ICS 2104 Object-Oriented Programming I
• Header Files
The next statement in the program is: #include<iostream.h> This statement is known
as a pre-processor directive. It instructs the pre-processor to retrieve the code stored
in iostream.h file and insert it at the point of #include statements. All files that have
.h extensions are officially called header files.
• Function Declaration
2. Name of function
Return type of function identifies the type of data that a function returns to its caller.
For example, a function can return to its caller a value of type int. In that case, int
is the return type of the function.
A function that does not return any data to its caller has void as its return type.
The name of function is any meaningful identifier as long as it not a reserved word.
The syntax of a function prototype is:
return_type_of_function name_of_function(list_of_parameters);
Note that the function prototype end with a semi-colon.
For example: int find_area(int length, int width);
Function prototype can be written with parameter names and without parameter
names
9
ICS 2104 Object-Oriented Programming I
For example: Without parameter names: int find_area(int, int); With parameter
names: int find_area(int length, int width); For a function that do not have parame-
ters, void keyword is used in place of parameter list For example: void find_area(void);
A function prototype let the compiler get to know the types of parameters, the num-
ber of parameters and order of parameters that a function will use. This information
enables it to detect type mismatch. Type mismatch is a situation whereby a function
is passed values that do not match with the type, the number order of the values that
a function expect. For a complex program, it is advisable to have all function pro-
totypes in separate header files. However, for simple programs function prototypes
can be included within the body of the program
• main() method
The remainder of the program is made of definition of the main() function. Function
definition has two pieces of information: a header and a body. The header provides
the function return type, the function name, followed by parentheses.
return type is the type of the value a function returns to its caller. The main()
function has int as its return type. The int value that main() function returns to
the operation system indicates whether the program has executed successfully or
not. It can return either zero(0) or one(1). Zero indicate successful execution of the
program and one indicate unsuccessful execution of the program.
The main() method is written in two forms:
• Form 1
int main(void) {
...
return 0;
}
• Form 2
10
ICS 2104 Object-Oriented Programming I
• Function Definitions
• Function definition has function body while function prototype does not have
function body
2.3. Testing
The main objective of testing a program is to uncover and remove errors. A suc-
cessful software test is the one that has enables one to uncover and remove errors in
a program. An error is a mistake that a program make when writing program source
code. Thare are different types of errors
• syntac errors( also known as compiler errors): Wrong use of the syntax rules.
These errors are easily detected by the compiler. A program that has syntax
errors does not compile
• run-time errors: These are errors that are uncovered when the program is
running.
11
ICS 2104 Object-Oriented Programming I
• logical errors: These errors are as a result of wrong logic. They are the most
difficult errors to uncover.
• cin>>memory_location1>>memory_location2>>...;
cout<<”string”;
cout is an object of type ostream that links a program to a standard output de-
vice(monitor), while cin is object of type istream which links a program with stan-
dard input device(keyboard).
The << operator insert characters into the cout for display while the >> operator
extract characters from the cin object and store them in memory locations. >>
operator is referred to as extraction operator while << operator is referred to as
insertion operator
Revision Questions
12
ICS 2104 Object-Oriented Programming I
13
ICS 2104 Object-Oriented Programming I
LESSON 3
Classes and Objects
Learning outcomes
Upon completing this topic you should be able to:
• Declare a class
14
ICS 2104 Object-Oriented Programming I
15
ICS 2104 Object-Oriented Programming I
The members functions declared within a class can be defined outside a class.
The definitions of these functions are just the same as definition of the normal func-
tions( functions that are not members of a class). But unlike normal functions mem-
ber functions defined outside a class definition are qualified with the name of the
class that they belong to. The name of the class and the member function are sepa-
rated using the scope resolution operator(: :).
The syntax of defining a member function outside a class is:
return-type class-name :: function-name (parameter list) { function body }
For instance, consider the print_dimension function declared in the Rectangle class
above. It may be defined as follows: void Rectangle :: print_dimension(void)
{
cout<<The Length is: “<<length <<”cm\n” <<”The width is : “<<width <<”cm\n”
<<endl;
}
Member functions can be defined within a class definition. Still consider the find_area()
function declared in the class Rectangle above.
This function can be defined in the class as shown below.
class Rectangle
{
private:
int length;
int width;
public:
void print_dimension(void)
{
cout<<”The Length is: “<<length <<”cm\n” <<”The width is : “<<width <<”cm\n”<<endl;
}
16
ICS 2104 Object-Oriented Programming I
};
Note:
• Form 1
class-name variable-name;
e.g.
Rectangle rect1;
b) Form 2
class-name variable-name(arguments);
e.g.
Rectangle rect2(4, 5);
The above two statements creates a class variables rect1 and rect2 of type Rectan-
gle. A class variable is an object. In that case rect1and rect2 are objects of type
Rectangle.
17
ICS 2104 Object-Oriented Programming I
18
ICS 2104 Object-Oriented Programming I
{
length=l;
width=w;
}
/* ————————————————————————————————
—–
Definition of print_dimension member function
—————————————————————————————————-
*/
void Rectangle :: print_dimension(void)
{
cout<<”The Length is: “<<length <<”cm\n” <<”The width is : “<<width <<”cm\n”
<<endl;
}
If you compile and execute this program, the output is
The Length is: 5cm The width is : 4cm
Revision Questions
19
ICS 2104 Object-Oriented Programming I
20
ICS 2104 Object-Oriented Programming I
LESSON 4
Friend Functions, Static Functions and Constant Functions
Learning outcomes
Upon completing this topic you should be able to:
private :
. . .
public :
f r i e n d void compute_tax ( Account ) ;
. . .
};
Note:
21
ICS 2104 Object-Oriented Programming I
22
ICS 2104 Object-Oriented Programming I
return 0;
}
23
ICS 2104 Object-Oriented Programming I
class B
{
private :
. . .
public :
. . .
f r i e n d i n t A : : y (B b ) ;
};
where
24
ICS 2104 Object-Oriented Programming I
25
ICS 2104 Object-Oriented Programming I
r e t u r n −t y p e f u n c t i o n −name ( )
{
c l a s s −name : : s t a t i c f u n c t i o n −name ( ) ;
}
Revision Questions
E XERCISE 13. Explain why friend functions are passed object of the class that
they have been to be a friend of
Example . Differentiate a member function and a friend function
Solution: A member function can access the data members of a class without using
an object while a friend function can only use an object to be able to access the data
member.
26
ICS 2104 Object-Oriented Programming I
27
ICS 2104 Object-Oriented Programming I
LESSON 5
Constructors and Destructors
Learning outcomes
Upon completing this topic you should be able to:
5.1. Constructors
A constructor is a member function that is used for creating objects and initializing
the states of the objects.
A constructor has the following characteristics:
• Its is the same as the name of the class within which it has been declared
• It is called automatically
28
ICS 2104 Object-Oriented Programming I
public:
Rectangle(int l, int w); //declaration of constructor
...
}; //definition of constructor
Rectangle::Rectangle(int l, int w)
{
length=l;
width=w;
}
• Default constructors
• Copy constructors
• Parameterized constructors
29
ICS 2104 Object-Oriented Programming I
30
ICS 2104 Object-Oriented Programming I
int width;
...
public:
Rectangle(int l, int w);
...
}; //definition of a parameterized constructor Rectangle::Rectangle(int l, int w) {
length=l; width=w; }
There are two ways of passing arguments to parameteized constructors when they
are called: by calling the constructor explicitly and by calling the constructor im-
plicitly. For example Rectangle rect1= Rectangle( 6, 5); //explicit call Rectangle
rect1(6, 5); //implicit call Implicit call is the one that is normally used.
5.5. Destructors
A destructor is a member function that is used to free a location that is held by an
object for use by another object.
An object is deleted when the flow of control leaves the scope within which it has
been created.
A destructor has the following properties
• It is not passed arguments and it does not have return type not even void
• It is called implicitly
31
ICS 2104 Object-Oriented Programming I
For example
Rectangle::~Rectangle()
{
cout<<”An object has been destroyed “<<endl;
}
Note that just like other member functions, constructors can have default arguments
and they can be overloaded.
Revision Questions
E XERCISE 18. Explain why a constructor is public and has no return type
E XERCISE 19. Differentiate a default constructor, a copy constructor and pa-
rameterized constructor
E XERCISE 20. Explain the difference between the following two statement:
Car myCar(200);
Car yourCar;
32
ICS 2104 Object-Oriented Programming I
33
ICS 2104 Object-Oriented Programming I
LESSON 6
Storage classes
Learning outcomes
Upon completing this topic you should be able to:
6.1. Introduction
In C++, just like in C, variables and functions have scope and lifetime.
The scope ( also referred to as visibility) of a variable or a function is a portion of
a program in which it is accessible while the lifetime of a variable or a function is
the duration of time that it exist during the execution of the program. Information
about scope and lifetime of variables and functions is provided by preceding their
declaration with the following storage class specifiers:
• auto
• register
• static
• extern
34
ICS 2104 Object-Oriented Programming I
}
All local variables are created and destroyed automatically.
The word auto is derived from their automatic creation and destruction.
All local variables are created when the block within which they have declared is
entered and destroyed when the block is exited. Parameters behavior like local
variables and therefore they are created and destroyed automatically.
Only local variables are associated with the auto storage class specifier.
Local variables and parameters have local lifetime and they are visible only in the
block of code they have been declared.
35
ICS 2104 Object-Oriented Programming I
block in which they are declared is exited. Variables that have global lifetime are
automatically initialization with zero.
Static keyword can also precede declaration of global variables. A global variable
is a variables that has been declared outside all the functions in a program.
In C++, functions can not be declared within other functions. Function can not be
declared at internal(local) level. All functions are declared at external(global) level
and therefore their their declaration can be preceded with static keyword. A static
function is only accessible within source file that it has been declared. Functions in
the same source file can call static functions but not functions in other source files.
Thereafter different source files can have static functions that have the same name.
Revision Questions
E XERCISE 22. Explain why a function can not be declared with auto and register
keyword
E XERCISE 23. Differentiate static and extern storage classes
E XERCISE 24. Explain the difference between external storage and internal stor-
age.
36
ICS 2104 Object-Oriented Programming I
1. .
37
ICS 2104 Object-Oriented Programming I
LESSON 7
Inheritance
Learning outcomes
Upon completing this topic you should be able to:
38
ICS 2104 Object-Oriented Programming I
39
ICS 2104 Object-Oriented Programming I
by the Car class. This means that public members of the class Vehicle become
public members of the class Car.
Consider the following definition of Car class
class Car: private Vehicle
{
.
.
.
};
In this case, the public members of Vehicle class become the private members of
the Car class.
The above definition of Car class is equivalent to the definition shown below.
class Car: Vehicle
{
.
.
.
};
The general format of defining a derived class is:
class className: memberAccessSpecifier baseClassName
{
.
.
.
};
where memberAccessSpecifier is public, protected or private. When no member-
AccessSpecifier is indicated, it is assumed to be private.
Note
private members of base class can not be inherited by the derived class
public members of base class can be inherited by derived class either as public or
private members of the derived class
Derived class has additional members
Derived class can redefine public members of the base class
40
ICS 2104 Object-Oriented Programming I
41
ICS 2104 Object-Oriented Programming I
virtual functions are only declared in the base class with the keyword virtual.
Example:
the calledclass that has been created or derived from another class can have a func-
tion that has been inherited from the based class having been redefined. Example
c l a s s Base {
public :
v i r t u a l void p r i n t ( ) {
c o u t < <" T h i s i s b a s e c l a s s "<< e n d l ;
}
};
A pure virtual function behaves just like a virtual function. However, it does not
have the body. It is declared in a base class. A class that has a pure virtual function
can not be instantiated. Such a class is also referred to as a abstract class. The
general format of declaring a pure virtual function is shown below:
virtual return-type function-name(parameters)=0;
example:
virtual void print(void)=0;
A class that is derived from an abstract class must defined pure virtual functions in
the base class. Otherwise the derived class will also be an abstract class.
Revision Questions
E XERCISE 25. Explain the difference between private and protected members
of a class
Example . Mark the following statements as true or false
a) The constructor of the derived class specify a call to the constructor of the base
class in the heading of defining derived class constructor
b) Inheritance is “has a” relation
c) public members of a base class can be inherited either as public or private by the
derived class
d) When initializing the objects of the derived class, the constructor of the base
class is executed last
Solution: a) true b) false c) true d) false
42
ICS 2104 Object-Oriented Programming I
43
ICS 2104 Object-Oriented Programming I
1.
44
ICS 2104 Object-Oriented Programming I
LESSON 8
Operator Overloading
Learning outcomes
Upon completing this topic you should be able to:
45
ICS 2104 Object-Oriented Programming I
c) ?:
d) sizeof
An operator overloading function may be either a member function or a non-member
function.
Non-member operator overloading functions are made to be friend function so that
they can access data members of other classes.
46
ICS 2104 Object-Oriented Programming I
And since the function is a member of Rectangle class, we have to call it using an
object that has been created from Rectangle class. Note also that operator+ function
must return a value which has to be assigned to rect3 variable.
This value is an object of type Rectangle.
Note that the compiler can not interpret line 3 as shown below Rectangle rect3=rect2.operator+(rect1);
Let us now write a complete program that as our operator+() function defined.
/∗−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
R e c t a n g l e . cpp T h i s p r o g r a m d e m o n s t r a t e s how b i n a r y
operators are overloaded
−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− ∗ /
# i n c l u d e < i o s t r e a m . h>
class Rectangle
{
private :
int length ;
public :
Rectangle ( i n t ) ;
void p r i n t _ v a l u e ( void ) ;
R e c t a n g l e o p e r a t o r +( R e c t a n g l e ) ;
};
/ / defining constructor outside
the class declaration
Rectangle : : Rectangle ( i n t l )
{ length=l ;
}
/ / defining operator overloading
function outside the class declaration
R e c t a n g l e R e c t a n g l e : : o p e r a t o r +( R e c t a n g l e r )
{
Rectangle rect ;
rect . length=length+r . length ; return rect ;
}
void Rectangle : : p r i n t _ v a l u e ( void )
{
47
ICS 2104 Object-Oriented Programming I
48
ICS 2104 Object-Oriented Programming I
49
ICS 2104 Object-Oriented Programming I
Rectangle rect1 ( 6 ) ;
Rectangle rect2 ( 7 ) ;
Rectangle rect3 = rect1 + rect2 ;
rect1 . print_value ();
rect2 . print_value ();
rect3 . print_value ();
return 0;
}
If you compile and execute this program, it will produce the following output on
the screen
The l e n g t h i s 6
The l e n g t h i s 7
The l e n g t h i s 13
50
ICS 2104 Object-Oriented Programming I
51
ICS 2104 Object-Oriented Programming I
Rectangle rect1 ( 6 ) ;
R e c t a n g l e r e c t 2 =++ r e c t 1 ;
rect1 . print_value ();
rect2 . print_value ();
return 0;
}
If you compile and execute this program, it will output the following on the screen.
The length is 7
The length is 7
52
ICS 2104 Object-Oriented Programming I
Rectangle ( i n t ) ;
void p r i n t _ v a l u e ( void ) ;
friend Rectangle operator ++();
};
/ / defining constructor outside the class declaration
Rectangle : : Rectangle ( i n t l )
{
length=l ;
}
/ / defining operator overloading function
outside the class declaration
R e c t a n g l e o p e r a t o r ++( R e c t a n g l e r e c t )
{
( r e c t . length )++;
return ∗ rect ;
}
void Rectangle : : p r i n t _ v a l u e ( void )
{
c o u t < <" The l e n g t h i s :" < < l e n g t h << e n d l ;
}
i n t main ( v o i d )
{
Rectangle rect1 ( 6 ) ;
R e c t a n g l e r e c t 2 =++ r e c t 1 ;
rect1 . print_value ();
rect2 . print_value ();
return 0;
}
If you compile and execute this program, it will output the following on the screen.
The length is 7
The length is 7
53
ICS 2104 Object-Oriented Programming I
54
ICS 2104 Object-Oriented Programming I
55
ICS 2104 Object-Oriented Programming I
square1 and zero (0) are values that are sent to operator++() function. Zero (0) is
used to distinguish between pre and post decrement/increment operator overload-
ing.
Zero (0) has no other use.
Below is an example of a program that shows how post-increment operation is
overloaded using a non-member function
/∗−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
R e c t a n g l e . cpp T h i s p r o g r a m d e m o n s t r a t e s
how u n a r y o p e r a t o r
is overloaded
−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
∗ / # i n c l u d e < i o s t r e a m . h>
class Rectangle
{
private :
int length ;
public :
Rectangle ( i n t ) ;
void p r i n t _ v a l u e ( void ) ;
f r i e n d R e c t a n g l e o p e r a t o r ++( R e c t a n g l e , i n t ) ;
};
/ / defining constructor outside the class declaration
Rectangle : : Rectangle ( i n t l )
{
length=l ;
}
/ / defining operator overloading function outside
the class declaration Rectangle operator
++( R e c t a n g l e r e c t , i n t dummy )
{
R e c t a n g l e temp =∗ t h i s ;
( r e c t . length )++;
r e t u r n temp ;
}
56
ICS 2104 Object-Oriented Programming I
57
ICS 2104 Object-Oriented Programming I
Note
1. cin and cout are objects of type istream and ostream respective.
2. operators<<() and operator>>() functions return objects of type ostream and
istream respectively.
Below is an example of a program, that demonstrates how insertion (<<) and ex-
traction (>>) operators are overloaded
/ ∗ −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
o v e r l o a d . cpp T h i s p r o g r a m d e m o n s t r a t e s
how t o o v e r l o a d i n s e r t i o n ( < <)
and e x t r a c t i o n ( > >) o p e r a t o r s
−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
∗/
\ # i n c l u d e < i o s t r e a m . h>
class Rectangle
{
private :
int length ;
public :
Rectangle ( i n t ) ;
f r i e n d o s t r e a m& o p e r a t o r <<
( o s t r e a m& o u t p u t , R e c t a n g l e r e c t 1 ) ;
f r i e n d i s t r e a m& o p e r a t o r >>
( i s t r e a m& i n p u t , R e c t a n g l e r e c t 2 ) ;
};
/ / defining constructor outside the class declaration
Rectangle : : Rectangle ( i n t l )
{
length=l ;
}
/ / defining operator overloading
function outside the class declaration
o s t r e a m& o p e r a t o r s < <( o s t r e a m& o u t p u t ,
Rectangle rect1 )
{
58
ICS 2104 Object-Oriented Programming I
o u t p u t << r e c t 1 . l e n g t h << e n d l ; r e t u r n o u t p u t ;
}
i s t r e a m& o p e r a t o r s < <( i s t r e a m& i n p u t , R e c t a n g l e r e c t 2 )
{
r e c t 2 >> r e c t 2 . l e n g t h ;
return input ;
}
i n t main ( v o i d )
{
Rectangle rect1 ( 6 ) ;
c o u t <<The v a l u e i s << r e c t 1 << e n d l ;
c o u t << E n t e r a v a l u e : ;
c i n >> r e c t 1 c o u t <<The v a l u e i s << r e c t 1 << e n d l ;
return 0;
}
If you compile and execute this program, the following will be displayed on the
computer screen.
The value is 6 Enter a value: 10 The value is 10
Revision Questions
59
ICS 2104 Object-Oriented Programming I
60
ICS 2104 Object-Oriented Programming I
61
ICS 2104 Object-Oriented Programming I
LESSON 9
Template
Learning outcomes
Upon completing this topic you should be able to:
• Define template
• Use templates
62
ICS 2104 Object-Oriented Programming I
c h a r swap ( c h a r ∗ a , c h a r ∗b )
{
c h a r temp =∗ a ;
∗ a =∗b ;
∗ b=temp ;
}
/ / t o v a l u e t h a t have decimal p o i n t s
d o u b l e swap ( d o u b l e ∗ a , d o u b l e ∗b )
{
d o u b l e temp =∗ a ;
∗ a =∗b ;
∗ b=temp ;
}
We have now defined three functions called swap. One function swaps values of
type int, the other swaps values of type char while the other swaps values of type
double. We have done that by overloading swap() function. However, the three
functions swap the values in the same way. In such a case instead of writing these
three functions, we could have written a function template and from this template
we can create these three function. This is a powerful concepts. In that case we can
create a swap function from our template that can be used to swap any data.
The syntax of declaring function template is:
template <class Type>
function-definition
Type is an identifier that is used to specify the following:
a) Type of arguments that will be passed to the function.
b) The return of the function
c) To declare variables within the function
For example
t e m p l a t e < c l a s s Type >
Type l a r g e r ( Type x , Type y )
{
i f ( x >= y )
return x;
63
ICS 2104 Object-Oriented Programming I
else
return y;
}
where template and class are reserved words.
Now we have declared a set of functions that are passed two arguments and return
the larger argument.
The types of parameters have not been specified.
This means we can pass to the larger() functions two arguments of the any data
types.
Below is a program that shows how function templates are used.
/∗−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
t e m p l a t e . cpp T h i s p r o g r a m d e m o n s t r a t e s
how f u n c t i o n t e m p l a t e i s u s e d −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
# i n c l u d e < i o s t r e a m . h>
/ / function template declaration
t e m p l a t e < c l a s s Type >
Type l a r g e r ( Type x , Type y ) ;
i n t main ( v o i d )
{
c o u t << p r i n t t h e l a r g e r v a l u e << l a r g e r ( 2 0 , 30) < < e n d l ;
c o u t << p r i n t t h e l a r g e r v a l u e << l a r g e r ( ’A’ , ’B’ ) < < e n d l ;
c o u t << p r i n t t h e l a r g e r v a l u e << l a r g e r ( 3 . 2 3 , 3.15) < < e n d l ;
return 0;
}
t e m p l a t e < c l a s s Type >
Type l a r g e r ( Type x , Type y )
{
i f ( x >= y )
return x;
else
return y;
}
64
ICS 2104 Object-Oriented Programming I
If you compile and execute this program it will display the following on the screen:
print the larger value 30
print the larger value B
print the larger value 3.23
65
ICS 2104 Object-Oriented Programming I
{
x= t y p e ;
}
/ / defining print_value outside the class declaration
t e m p l a t e < c l a s s Type >
v o i d Number<Type > : : p r i n t _ v a l u e ( v o i d )
{
c o u t <<The v a l u e i s <<x<< e n d l ;
}
If you compile and execute this program it will print the following on the screen
The value is 20 The value is A The value is 3.14
Revision Questions
E XERCISE 33. Suppose cType is a class template and func is a member function
of cType. Show the heading of the function definition of func
Example . Suppose cType is a class template, which can take int as a parameter.
Explain what the statement below means. cType<int> y;
Solution: it declares y to be an object of the type cType, and the type passed to the
class cType is int
66
ICS 2104 Object-Oriented Programming I
...
private:
type a;
type b;
};
Write a statement that declares sobj to be an object of the type strange such that the
private data members a nd b are of type int
E XERCISE 36. Consider the definition of the following function template
template <class type>
type surprise(type x, type y)
{
return x+y;
}
What is the output of the following statement
a) cout<<surprise(5, 7)<<endl;
b)
string str1=”sunny”;
string str2=”day”;
cout<<surprise(str1, str2)<<endl;
67
ICS 2104 Object-Oriented Programming I
68
ICS 2104 Object-Oriented Programming I
LESSON 10
Files and Streams
Learning Outcomes
Upon completing this topic, you should be able to:
10.1. Introduction
Many programs use large data sets that is stored in secondary memory
The data is stored in files.
There are two basic types of files:
10.2. Stream
A stream is a sequence of characters. It is the one that links a program to a file. In
object-oriented programs, stream are objects. In C++ streams are objects of type
fstream. fstream is the name of a class that is stored in fstream.h file.
An object of type fstream is declared as shown below:
fstream inputFile;
fstream outputFile;
where:
fstream is a keyword
inputFile and outputFile are names of the streams that are to be linked to files.
69
ICS 2104 Object-Oriented Programming I
For example:
fstream outputfile(“myfile1.cpp”, ios::out); //output file,
fstream inputfile(“myfile2.cpp”, ios::in); //input file.
Where
myfile1.cpp and myfile2.cpp are the names of files that are being opened.
ios::in and ios::out are file open modes for reading and writing respectively.
myfile1.cpp is opened for reading and myfile2.cpp is opened for writing
70
ICS 2104 Object-Oriented Programming I
71
ICS 2104 Object-Oriented Programming I
72
ICS 2104 Object-Oriented Programming I
When a file is opened for reading, the get pointer is automatically positioned at the
beginning of the file. Similarly when a file is opened for writting the put pointer
is positioned at the beginning of the file. These pointers are moved to any desired
positions through the use of seekg() , seekp(), tellg() and tellp() functions. seekg()
and seekp() moves the positions of get and put pointers respectively while tellg()
and tellp() returns the current positions of get and put pointers respectively. Seekp()
and seekg() are passed two arguments. The first argument is always the number
of bytes that the pointer is to be moved, while the second argument is the position
where the movement should begin. There are three constants that are used to denote
the position where the movement should begin. These constants are: ios::beg //this
means the movement should start at the beginning of the file ios::cur//this means
the movement should start at the current position of the pointer ios::end//this means
the movement should start at the end of the file Note, the movement can be either
backward or forward starting at the specified position. This is done by preceding
the number of bytes to be moved with either a plus(+)for forward or a minus (-) for
backward. For example inputfile.seekg(0, ios::beg); //go to the beginning of the file
inputfile.seekg(m, ios::cur); //move m bytes starting at the current position
Revision Questions
E XERCISE 38. Write a program that prompts a user to enter that name of a file.
The program should display the content of the file on the screen
E XERCISE 39. Write a program that counts and print the number of words in a
file. The program should prompt a user to input the name of a file
E XERCISE 40. Explain the various file opening mode
73
ICS 2104 Object-Oriented Programming I
74
ICS 2104 Object-Oriented Programming I
Solutions to Exercises
Exercise 1. a class is a collection of objects that have similar properties while an
object is an instance of a class Exercise 1
Exercise 5. comments improve readability/understandability of a program. They
enables other programmers to understand the program better Exercise 5
Exercise 9.
The object enables friend function to access the data members of the class.
Exercise 13
Exercise 17. A constructor creates objects while a destructor destroy objects
Exercise 17
Exercise 21. Scope of a variable is the portion of the program within which a
variable is accessible while life-time of a variable is the duration of time that a
variable exist in the program
Exercise 21
Exercise 25. private members of a class can not be inherited by a derived class
while protected members can be inherited by a derived class Exercise 25
Exercise 29. A friend function is a function that is not a member of a class but it
has access to the data member of the class Exercise 29
Exercise 33. template<class Type> functionReturnType cType<Type>:: func(parameters);
Exercise 33
Exercise 37. A stream is a sequnce of characters. It is a link between a file and
a program. In object-oriented programs, stream are objects that connect programs
with files. They are the ones that enables programs to read from or write to a file
Exercise 37
75