C++ Practical Manual
C++ Practical Manual
PRACTICAL MANUAL
BY
OMOREGIE K. O.
ANYAORAH I. E.
ALIU ABASS
OYANIRAN O. FEM I
FOR
NAME:- ___________________________________________________________________
MATRIC NUMBER:- _______________________________________________________
LEVEL:- ___________________________________________________________________
DEPARTMENT:- ___________________________________________________________
GROUP:- __________________________________________________________________
Copyright © 2019 K. O. OMOREGIE, ANYAORAH I. E., ABASS ALIU & OYANIRAN O. FEMI
ISBN 941-23150-3-6
i
TABLE OF CONTENTS
LESSON ONE................................................................................................................................................................. 1
INTRODUCTION TO C++ PROGRAMMING IDE....................................................................................................................1
STUDENTS UNGUIDED PRACTICE 1....................................................................................................................................3
LESSON TWO................................................................................................................................................................ 4
THE STRUCTURE OF A C++ PROGRAM...............................................................................................................................4
STUDENTS UNGUIDED PRACTICE 2....................................................................................................................................6
LESSON THREE.............................................................................................................................................................. 7
FUNDAMENTAL DATA TYPES IN C++..................................................................................................................................7
STUDENTS UNGUIDED PRACTICE 3..................................................................................................................................10
LESSON FOUR.............................................................................................................................................................. 11
DATA INPUT AND OUTPUT IN C++...................................................................................................................................11
STUDENTS UNGUIDED PRACTICE 4..................................................................................................................................12
LESSON FIVE................................................................................................................................................................ 13
CONTROL STRUCTURES....................................................................................................................................................13
STUDENTS UNGUIDED PRACTICES 5................................................................................................................................19
LESSON SIX................................................................................................................................................................. 20
C++ PROGRAM WITH FUNCTIONS AND LIBRARIES...........................................................................................................20
LESSON SEVEN............................................................................................................................................................ 24
CLASSES AND OBJECTS.....................................................................................................................................................24
STUDENT UNGUIDED PRACTICE.......................................................................................................................................27
LESSON EIGHT............................................................................................................................................................. 28
FRIENDSHIP AND INHERITANCE.......................................................................................................................................28
STUDENT UNGUIDED PRACTICE.......................................................................................................................................32
LESSON NINE............................................................................................................................................................... 33
CONCEPT OF POLYMORPHISM.........................................................................................................................................33
STUDENT UNGUIDED PRACTICE.......................................................................................................................................35
LESSON TEN................................................................................................................................................................ 36
POINTERS AND ARRAY IN C++ PROGRAMS......................................................................................................................36
STUDENT UNGUIDED PRACTICE.........................................................................................................................................38
ii
LESSON ONE
INTRODUCTION TO C++ PROGRAMMING IDE
OBJECTIVES:
1. Students should be able to create new program using CodeBlocks IDE
2. Students should also be able to open existing programs
INTRODUCTION
The task below demonstrates how to load C++ program using Code::Blocks 10.05 on Windows
Operating System
1) Click on Start Button on the taskbar 2) Click all Programs/Programs
3) Click CodeBlocks folder 4) Click on CodeBlocks, it will automatically open
Click on Next
Click on Finish
Locate the Project tab on the Management Window, Click on the “+” symbol beside the Sources
folder
Double click on main.cpp
You have an auto generated source file which you edit using your own code.
OR
Click on File and then click on Recent Projects and select your project name.
2
STUDENTS UNGUIDED PRACTICE 1
1. What is/are the difference between source code and object code?
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
2. State the steps to create a new console source file in CodeBlocks?
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
3
LESSON TWO
THE STRUCTURE OF A C++ PROGRAM
OBJECTIVES
1. Students should be able to identify and explain the basic components of a C++ program
Probably the best way to start learning a programming language is by writing a program. Therefore, here
is our first program
SAMPLE C++ PROGRAM
SOURCE CODE
OUTPUT
Hello World!
This program displays on the screen "Hello World!". It is one of the simplest programs that can be written
in C++, but it already contains the fundamental components that every C++ program has.
EXPLANATIONS
1. // my first program in C++
This is a comment line. All lines beginning with two slash signs (//) are considered comments and do not
have any effect on the behavior of the program. The programmer can use them to include short
explanations or observations within the source code itself. In this case, the line is a brief description of
what our program is.
2. #include <iostream>
Lines beginning with a hash sign (#) are directives for the preprocessor. They are not regular code lines
with expressions but indications for the compiler's preprocessor. In this case the directive #include
<iostream> tells the preprocessor to include the iostream standard file. This specific file (iostream)
includes the declarations of the basic standard input-output library in C++, and it is included because its
functionality is going to be used later in the program.
4. int main ()
This line corresponds to the beginning of the definition of the main function. The main function is the
point by where all C++ programs start their execution, independently of its location within the source
code. It does not matter whether there are other functions with other names defined before or after it –
4
the instructions contained within this function's definition will always be the first ones to be executed in
any C++ program. For that same reason, it is essential that all C++ programs have a main function.
The word main is followed in the code by a pair of parentheses (()). That is because it is a function
declaration: In C++, what differentiates a function declaration from other types of expressions are these
parentheses that follow its name. Optionally, these parentheses may enclose a list of parameters within
them.
Right after these parentheses we can find the body of the main function enclosed in braces ( {}). What is
contained within these braces is what the function does when it is executed.
6. return 0;
The return statement causes the main function to finish. return may be followed by a return code (in our
example is followed by the return code 0). A return code of 0 for the main function is generally
interpreted as the program worked as expected without any errors during its execution. This is the most
usual way to end a C++ console program.
You may have noticed that not all the lines of this program perform actions when the code is executed.
There were lines containing only comments (those beginning by //). There were lines with directives for
the compiler's preprocessor (those beginning by #). Then there were lines that began the declaration of a
function (in this case, the main function) and, finally lines with statements (like the insertion into cout),
which were all included within the block delimited by the braces ({}) of the main function.
The program has been structured in different lines in order to be more readable, but in C++, we do not
have strict rules on how to separate instructions in different lines. For example, instead of
int main ()
{
cout << " Hello World!";
return 0;
}
We could have written:
int main () { cout << "Hello World!"; return 0; }
All in just one line and this would have had exactly the same meaning as the previous code.
In C++, the separation between statements is specified with an ending semicolon (;) at the end of each
one, so the separation in different code lines does not matter at all for this purpose. We can write many
statements per line or write a single statement that takes many code lines. The division of code in
different lines serves only to make it more legible and schematic for the humans that may read it .
(Source: Juan Soulié, 2007, cplusplus.com)
5
STUDENTS UNGUIDED PRACTICE 2
6
LESSON THREE
FUNDAMENTAL DATA TYPES IN C++
OBJECTIVES:
1. Students should be able to use the different data types in C++.
2. Students should be able to define and identifiers and Constant in C++.
3 Students should be able to manipulate the different operators in C++.
INTRODUCTION
Data types are means to identify the type of a data and the associated operations for handling it. C++
provides a predefined set of data types for handling the data it uses. Data can be of many types such as
character, integer, float etc.
Variable can be described as a named memory location in the computer system used to store and
manipulate values in a computer program. It is also defined as values that are subject to change during
program execution. They are sometimes called Identifiers.
Rules in forming a valid variable (identifier) name in C++ program
1. A variable name must begin with a letter or an underscore “_”.
2. Subsequent characters can be alphanumeric (combination of letters and digits).
3. It can be embedded with underscore, e.g. first_pro.
4. Keywords or reserved words must not be used as variables.
5. It must not contain space or punctuation marks.
Examples:
VALID: a, auchi4life, my_age, score1, SCORE, etc.
INVALID: 2, 5star, my age, score.1, float, etc.
Fundamental data types
NAME DESCRIPTION SIZE RANGE
char Character or small integer. 1byte signed: -128 to 127
unsigned: 0 to 255
short int Short integer 2 bytes signed: -32768 to 32767
(short) unsigned: 0 to 65535
Int Integer 4 bytes signed: -2147483648 to 2147483647
unsigned: 0 to 4294967295
long int (long) Long integer 4 bytes signed: -2147483648 to 2147483647
unsigned: 0 to 4294967295
bool Boolean value. It can take one of two values: true 1 byte true or false
or false.
float Floating point number. 4 bytes +/- 3.4e +/- 38 (~7 digits)
double Double precision floating point number. 8 bytes +/- 1.7e +/- 308 (~15 digits)
long double Long double precision floating point number. 8 bytes +/- 1.7e +/- 308 (~15 digits)
wchar_t Wide character. 2 or 4 bytes 1 wide character
The values of the columns Size and Range depend on the system the program is compiled for. The values
shown above are those found on most 32-bit systems.
7
The first one, known as c-like, is done by appending an equal sign followed by the value to which the
variable will be initialized:
type variable_name = initial_value ;
For example, if we want to declare an int variable called amount initialized with a value of 100 at the
moment in which it is declared, we could write:
int amount = 100;
The other way to initialize variables, known as constructor initialization, is done by enclosing the initial
value between parentheses ( ):
type identifier (initial_value) ;
Example:
int amount (100);
3. Compound assignment operators(+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)
Score = score + 5; This can also be written as score += 5;
Same thing applies to other compound assignment operators.
4. Increase and decrease (++, --)
This is short method for increasing or decreasing a variable by.
Example: age++ or ++age; is equivalent to age = age + 1;
same thing applies to –-.
Note: When used in an expression, the prefix format, ++age, will add 1 to age and use the new value of
age in the expression evaluation. But when used in suffix format, age++, the value of age will be used to
evaluate the expression before 1 is added to age.
Example:
age = 10;
newAge = age++; (newAge will be 10 while age will be 11)
age = 10;
newAge = ++age; (newAge will be 11 and age will be 11)
5. Relational and equality operators (==, !=, >, <, >=, <=)
In order to evaluate a comparison between two expressions we can use the relational and equality
operators. The result of a relational operation is a Boolean value that can only be true or false, according
to its Boolean result.
Example: assuming that val1 = 2, val2 = 3, and val3 = 6
(val1 == 5) // evaluates to false since a is not equal to 5.
(val1 * val2 >= val3) // evaluates to true since (2*3 >= 6) is true.
(Val2 + 4 > val1*val3) // evaluates to false since (3+4 > 2*6) is false.
((val2 = 2) == val1) // evaluates to true.
6. Logical operators (!, &&, ||)
8
The operator ! is the C++ operator to perform the Boolean operation NOT. Basically, it returns the
opposite Boolean value of evaluating its operand.
Example:
!(5 == 5) // evaluates to false because the expression at its right (5 == 5) is true.
!(6 <= 4) // evaluates to true because (6 <= 4) would be false.
!true // evaluates to false
!false // evaluates to true.
The logical operators && and || are used when evaluating two expressions to obtain a single
relational result. The operator && corresponds with Boolean logical operation AND while ||
corresponds to logical operation OR.
Example:
((5 == 5)&& (3 > 6)) // evaluates to false (true && false).
((5 == 5)||(3 > 6)) // evaluates to true (true || false).
7. Conditional operator (?)
The conditional operator evaluates a conditional expression and returns the first value after the
conditional operator ? if that expression is true and returns the second value if the expression is
evaluated as false. Its format is:
condition ? result1 : result2
7==5 ? 4 : 3 // returns 3, since 7 is not equal to 5.
5>3 ? a : b // returns the value of a, since 5 is greater than 3.
8. Comma operator (,)
The comma operator (,) is used to separate two or more expressions that are included where only one
expression is expected
Example
a = (b=3, b+2);
Would first assign the value 3 to b, and then assign b+2 to variable a. So, at the end, variable a would
contain the value 5 while variable b would contain value 3.
Constants
Like variables, constants are also memory locations which are not subject to change during program
execution. C++ has two types of constants: Literal and Symbolic Constant.
(a) Literal Constants
Literals are the most obvious kind of constants. They are used to express particular values within the
source code of a program. It can be values of Integer Numerals (e.g. x = 43), Floating-Point Numerals; (e.g.
y = 23.43), Characters; (e.g. sex = ‘F’), Strings; (e.g. name = “Mandela”) and Boolean; (e.g.
completed = true).
(b) Symbolic Constants
This is one of the constant that is represented by a name, just as a variable is.
Defining Symbolic Constants with #define
#define PI 3.14159
This defines a new constant PI. Once it is defined, you can use it in the rest of your code as any other
regular constant.
Example:
int r = 5;
Area = PI * r * r;
#define is a preprocessor command, hence it is processed before compilation starts. This will mean
that everywhere PI is used in the program, it will be changed to 3.14159 before compilation starts. In
other words, it is not too different from the literal constants in principle.
Defining Constants with const
With the const prefix, you can declare constants with a specific type in the same way as you would do
with a variable. Example: const int price = 3000;
9
const, unlike #define, will reserve a memory space named PI just like variables, but the value of the
memory space remain the same throughout the program execution.
2. Write a simple program in C++ using #define to declare a constant and show what the program
will look like before compilation starts, i.e, after the preprocessing.
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
3. Rewrite the program you wrote in question using the const to define the constant
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
10
LESSON FOUR
DATA INPUT AND OUTPUT IN C++
OBJECTIVES:
1. Students be able to perform basic input and output operations in C++
2 Students should know the various types of errors in programming
INTRODUCTION
C++ uses a convenient abstraction called streams to perform input and output operations in sequential
media such as the screen or the keyboard. A stream is an object where a program can either insert or
extract characters to/from it.
Standard Output (cout)
By default, the standard output of a program is the screen, and the C++ stream object defined to access
the cout.
cout is used in conjunction with the insertion operator, which is written as << (two "less than" signs).
Example:
cout << "Output sentence"; // prints “Output sentence” on screen
cout << 120; // prints number 120 on screen
The insertion operator (<<) may be used more than once in a single statement:
cout << "Hello," << "I am" << "in C++ Practical Class";
This last statement would print the message “Hello, I am in C++ Practical Class” on the screen.
Standard Input (cin).
The standard input device is usually the keyboard. Handling the standard input in C++ is done by
applying the overloaded operator of extraction (>>) on the cin stream. The operator must be followed by
the variable that will store the data that is going to be extracted from the stream. For example:
int age;
cin >> age;
The first statement declares a variable of type int called age, and the second one waits for an input from
cin (the keyboard) in order to store it in this integer variable.
11
STUDENTS UNGUIDED PRACTICE 4
1. Dry run the program code below and detect the bugs, if any. Type, compile and print the source
code and the program output. Your output must reflect correct results.
#include<io stream>
main ()
using namespace std;
{
Int a, b, c, d, f
Float e;
cout<<”Enter value for a”
cin>>a;
cout<<”Enter value for b”;
cin>>b
c = a + b;
d = a * b
e = (a + b)/2;
f = a – b
cout<<”The Addition is :”<<d<<”\n”
cout<<”The Substraction is :”<<c<<”\n”;
cout<<”The Multiplication is :”<<e<<”\n”;
cout<<”The Division is :”<<f<<”\t”;
}
2. Write a program to accept the name of a student and his/her scores in English, Mathematics,
Physics and Economics as inputs, and computes the average score of the student. Display, as
output, the name of the student and the average score.
Hint: To avoid data loss, use appropriate data type for the average.
12
LESSON FIVE
CONTROL STRUCTURES
OBJECTIVES:
1. Students should be able to understand the various control statements in C++
2. They should be able to differentiate between the types of control statements in C++
3. They should be able to write programs using the appropriate control statements.
INTRODUCTION
A program is usually not limited to a linear sequence of instructions. During its process it may repeat
statement (iterate) or take decisions. For that purpose, C++ provides control structures that serve to
specify what has to be done by our program, when and under which circumstances.
Conditional Structure:
The conditional structure consists of statements that alter the sequential flow of a program under a
specified condition. It can either be in the form of SELECTION or ITERATION/LOOP
Selection Structure
if statement
The if keyword is used to execute a statement or block only if a condition is met. Its form is:
if (condition) statement;
If this condition is true, statement is executed. If it is false, statement is not executed and the program
continues to the next line after the if construct.
Type and execute this if program in your computer. What did you observed?
#include<iostream>
using namespace std;
main (){
int n, d;
cout<<"Enter the two integers\n";
cin>>n>>d;
if(n%d==0)
cout<<n<<" is divisible by "<<d<<" Stop the program"<<\n;
return 0;
}
If …else Statement
We can additionally specify what we want to happen if the condition is not fulfilled by using the
keyword else. Its form used in conjunction with if is:
if (condition)
statement1 if condition is met
else
statement2 if condition is not met
13
Write these programs below in C++ source file and execute them. What did you observe?
#include<iostream>
using namespace std;
main ()
{
int n, d;
cout<<"Enter two integer\n";
cin>>n>>d;
if(n%d==0)
cout<<n<<" is divisible by "<<d<<"\t";
else
cout<<n<<" is not divisible by "<<d<<"\t";
return 0;
}
…………………………………………………………………………………………………………………………………….
#include<iostream>
#include<math>
using namespace std;
int main()
{
int score;
cout<<"Enter the test score\n";
cin>>score;
if(score>=80) cout<<"The test score is Excellent\t";
else if(score>=60)cout<<"The test score is Good\t";
else if(score>=40)cout<<"The test score is Fair\t";
else cout<<"The test score is Bad\t";
return 0;
}
Switch Statement.
The syntax of the switch statement is a bit peculiar. Its objective is to check several possible constant
values for an expression. Its form is as follows:
switch (expression){
case constant1:
group of statements 1;
break;
case constant2:
group of statements 2;
break;
.
.
.
default:
default group of statements
}
Switch evaluates expression (expression must evaluate to int or char) and checks if it is equivalent to
constant1, if it is, it executes group of statements 1 until it finds the break statement. When it finds this
break statement the program jumps to the end of the switch structure.
If expression was not equal to constant1 it will be checked against constant2. If it is equal to this, it will
execute group of statements 2 until a break keyword is found, and then will jump to the end of the switch
structure.
Finally, if the value of expression did not match any of the previously specified constants (you can include
as many case labels as values you want to check), the program will execute the statements included after
the default: label, if it exists (it is optional).
14
Without the break statement, the execution continues into the next case until it gets to the end of the
switch structure.
Consider the program below that displays the name of the calendar month when its numeric value is
entered. There would be twelve possibilities, one for each month. The month’s value is stored in an
integer variable month.
int month;
cin>>month;
switch (month) {
case 1: cout << "January";
break;
case 2: cout << "February";
break;
case 3: cout << "March";
break;
case 4: cout << "April";
break;
// and so on for the other months
case 12: cout << “December”;
break;
default: cout <<”Wrong month number entered”;
}
Iteration/Loop Structure
15
int main(){
int counter;
cout<<"How many Hellos" ;
cin>>counter;
do{
cout<<"Hello\n";
counter--;
}while(counter<0);
cout<<"Counter is:"<<counter<<endl;
return 0;
}
Do you understand the use of do… while statement above?
Type the program below
Compile and Execute the program
Dry run the program to make sure you understand what it does
#include<iostream>
using namespace std;
main (){
int n, f=1;
cout<<"Enter a positive integer\n";
cin>>n;
cout<<n<<" Factorial is ";
do{
f*=n;
n--;
}
while(n>1);
cout<<f<<endl;
return 0;
}
Dry run the program below and check for any bug. If any, debug the program and note your observation
//This program displays and counts the numbers of Hello’s
#include<iostream>
using namespace std;
int main () {
int counter;
cout<<"How many Hellos\n" ;
cin>>c
do{
cout<<"Hello\n";
counter;
}while(counter<0);
cout<<"Counter is:"<<counter<<endl;
return
}
For statement
Its format is:
for (initialization; condition; increase) statement;
It repeats statement while condition remains true, like the while loop. But in addition, the
16
for loop provides specific locations to contain an initialization statement and an increase statement. So
this loop is specially designed to perform a repetitive action with a counter which is initialized and
increased on each iteration.
It works in the following way:
1. Initialization of the counter variable is executed. This is executed only once.
2. Condition is checked. If it is true the loop continues, otherwise the loop ends and statement is skipped
3. Statement is executed. As usual, it can be either a single statement or a block enclosed in braces { }.
4. Finally, whatever is specified in the increase field is executed and the loop gets back to step 2.
#include<iostream>
using namespace std;
main (){
int n, sum=0;
cout<<"Supply a positive integer\n";
cin>>n;
for(int i=1; i<=n; i++);
sum+=i*i;
cout<<"The Sum of the first "<<n<<" Square is "<<sum<<endl;
return 0;
}
Do you understand the use of for statement above?
Enter the program below into C++ source file
Compile and Execute the program
#include<iostream>
using namespace std;
int main(){
for(int i=32; i<128; i++)
cout<<(char)i<<"\t";
return 0;
}
Unconditional Structure:
The unconditional control structures alter the flow of a sequential flow without a condition attached.
They can stand alone as a statement unlike conditional structure that are tied to conditions to make
selection or to loop. It is possible however, to have unconditional structure as part of the statement
body of a conditional structure.
#include <iostream>
using namespace std;
int main(){
int n=10;
loop:
cout << n << ", ";
n--;
if(n>0) goto loop;
cout << "FIRE!\n";
17
return 0;
}
#include <iostream>
using namespace std;
int main (){
int n;
for (n=10; n>0; n--){
cout << n << ", ";
if (n==3){
cout << "countdown aborted!";
break;
}
}
return 0;
}
18
(Source: Juan Soulié, 2007, cplusplus.com; Tony Jenkins, 2003, How to Program Using C++)
2. State the difference between the while statement and do... while statement.
_______________________________________________________________________________________________________________
_______________________________________________________________________________________________________________
_______________________________________________________________________________________________________________
_______________________________________________________________________________________________________________
_______________________________________________________________________________________________________________
_______________________________________________________________________________________________________________
_______________________________________________________________________________________________________________
_______________________________________________________________________________________________________________
3. Write a program to display even numbers between 1 and 20, using do… while statement. Print
your source code and the output.
4. Using if … else statement, write a program to calculate the Total Score of a student in
COM313 and output the student’s grade using the scales listed below.
Hint: Total Score = CW + Exam.
Print out the source file and output.
75 – 100 A
70 – 74 AB
65 – 69 B
60 – 64 BC
55 – 59 C
50 – 54 CD
45 – 49 D
40 - 44 E
00 - 39 F
19
LESSON SIX
C++ PROGRAM WITH FUNCTIONS AND LIBRARIES
OBJECTIVES
1. Students should understand the concept of function.
2. They should know how to use C++ libraries
INTRODUCTION
A function is a group of statements that together perform a task. Every C++ program has at least one
function which is called main from which program execution starts and link to any other defined
function.
A C++ function definition consists of a function header (consisting of function name, return type, and
parameters) and a function body.
Return Type: A function may return a value. The return-type is the data type of the value the
function returns. Some functions perform the desired operations without returning a value. In
this case, the return-type is the keyword void.
Function Name: This is the actual name of the function. The function name and the parameter
list together constitute the function signature.
Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to
the parameter. This value is referred to as actual parameter or argument. The parameter list
refers to the type, order, and number of the parameters of a function. Parameters are optional;
that is, a function may contain no parameters.
Function Body: The function body contains a collection of statements that define what the
function does.
20
}
21
Annotation
Line 3: float volume(float radius, float height);
This line declares the function interface. It starts with the return type of the function (float in this
case). The function name volume appears next followed by its parameter list. circumference has two
parameters (radius and height) which are of types float. Note that the syntax for parameters is
similar to the syntax for defining variables: <type identifier> followed by the <parameter name>.
However, it is not possible to follow a type identifier with multiple comma-separated parameters:
float volume (float radius, height) // Wrong!
Line 12: float volume(float radius, float height)
This is the beginning of the function definition. Function definition includes the body of the function.
Line 12: The opening brace “{“ immediately after the function header marks the beginning of the
function body.
Line 13: This is a local constant definition. Constants and variables declared within a function are visible
only within the function.
Line 14: This statement computes the volume and returns the result to the calling program (main).
Line 15: This brace marks the end of the function body.
Line 8: This illustrates how the volume function is called. The arguments r and h are respectively
assigned to the parameters radius and height, and then the function body is evaluated. The value
returned by the volume function is displayed in Line 8 as the program output.
22
j. bool isspace(char) true if the character is a space
k. bool isalpha(char) true if the character is alphabetic
l. bool isalnum(char) true if the character is alphanumeric
m. bool isdigit(char) true if the character is a digit
n. bool isupper(char) true if the character is an upper case letter
o. bool islower(char) true if the character is a lower case letter
p. char toupper(char) returns upper case equivalent of character if appropriate
q. char tolower(char) returns lower case equivalent of character if appropriate
These functions are called in exactly the same way as non-member functions. Functions a to i require the
inclusion of cmath header file from the library. The pow function for example is used below as
#include <iostream>
#include <cmath>
using namespace std;
int main(){
float x;
x = 6.0;
cout << "\n 6 power 2 = " << pow(x,2);
return 0;
}
Functions j to q require the inclusion of cctype header file from the library. The pow function for
example is used below as
#include <cctype>
#include <iostream>
using namespace std;
int main (){
char ch = 'a';
cout << ch << endl; // outputs 'a'
ch = toupper(ch); // converts ch to upper case
cout << ch << endl; // outputs 'A'
return 0;
}
23
(Sources: Juan Soulié, 2007, cplusplus.com; Tony Jenkins, 2003, How to Program Using C++)
24
STUDENT UNGUIDED PRACTICE 6
1. Write a program to find the factorial of a given integer number. The program is should have a
user defined function called factorial. Print the source code and the output.
2. Write a program of your choice to demonstrate your understanding of any of the string
functions. Print the source code and the output.
3. Write a program of your choice to demonstrate your understanding of any of the cmath
functions. Print the source code and the output.
4. Write a program of your choice to demonstrate your understanding of any of the cctype
functions. Print the source code and the output.
5. Research on parameter passing techniques in C++ and write a program to demonstrate the
difference between parameter passing by value and parameter passing by reference. Print the
source code and the output.
LESSON SEVEN
CLASSES AND OBJECTS
OBJECTIVES
1 Students should be able to use define classes and declare their objects.
2 They should also be able to manipulate objects to solve a giving program task.
3 Students should understand and make use of constructors.
INTRODUCTION
You create a new type by declaring a class. A class is just a collection of variables--often of different
types--combined with a set of related functions. A class can consist of any combination of the variable
types and also other class types. The variables in the class are referred to as the member variables or data
members. The functions in the class typically manipulate the member variables. They are referred to as
member functions or methods of the class.
Declaring a Class
Classes are generally declared using the keyword class, with the following format:
class class_name {
access_specifier_1:
member1;
access_specifier_2:
member2;
...
} object_names;
Where class_name is a valid identifier for the class, object_names is an optional list of names for
objects of this class. The body of the declaration can contain members, that can be either data or function
declarations, and optionally access specifiers. An access specifier is one of the following three
keywords: private, public or protected. These specifiers modify the access rights that the
members following them acquire:
• private members of a class are accessible only from within other members of the same class or from
their friends.
• protected members are accessible from members of their same class and from their friends, but also
from members of their derived classes.
• Finally, public members are accessible from anywhere where the object is visible.
By default, all members of a class declared with the class keyword have private access for all its members.
Here's the declaration of a class called Rectangle:
class Rectangle{
public:
unsigned int length;
unsigned int breadth;
void getArea();
void getPerimeter();
};
Declaring this class doesn't allocate memory for a Rectangle. It just tells the compiler what a Rectangle
is, what data it contains (length and breadth), and what it can do (getArea() and
getPerimeter()). It also tells the compiler how big a Rectangle is--that is, how much room the
compiler must set aside for each Rectangle that you create. In this example, if an integer is two bytes, a
Rectangle is only four bytes big: length is two bytes, and breadth is another two bytes. getArea()
and getPerimeter() takes up no room, because no storage space is set aside for member functions
(methods).
Defining Object of a Class.
To define an object of class, you specify the name of the class followed by the name you want to give the
object.
Example: Rectangle smallRectangle;
In the same way, to call the getArea() function, you would write
smallRectangle.getArea();
(Source: Gred Wiegand, 2007, Teach Yourself C++ in 21 Days, 2nd Edition)
SAMPLE CODE
int main()
{
Rectangle smallRectangle;
smallRectangle.setValues(5,3);
smallRectangle.getArea();
smallREctangle.getPerimeter();
return 0;
}
void Rectangle::getArea(){
cout << “Area = “ << length * breadth;
}
void Rectangle::getPerimeter(){
cout << “Perimeter = “ << 2*(length + breadth);
}
OUTPUT
Area = 15
Perimeter = 16
Constructors and destructors
Objects generally need to initialize variables or assign dynamic memory during their process of creation
to become operative and to avoid returning unexpected values during their execution. For example, what
would happen if in the previous example we called the member function getArea() before having
called function setValues()? Probably we would have gotten an undetermined result since the
members length and breadth would have never been assigned a value.
In order to avoid that, a class can include a special function called constructor, which is automatically
called whenever a new object of this class is created. This constructor function must have the same name
as the class, and cannot have any return type; not even void.
We are going to implement Rectangle including a constructor:
int main()
{
Rectangle smallRectangle(5,3);
smallRectangle.getArea();
smallREctangle.getPerimeter();
return 0;
}
void Rectangle::getArea(){
cout << “Area = “ << length * breadth;
}
void Rectangle::getPerimeter(){
cout << “Perimeter = “ << 2*(length + breadth);
}
We have removed the member function setValues(), and have included instead a constructor that
performs a similar action: it initializes the values of length and breadth with the parameters that are
passed to it. Notice how these arguments are passed to the constructor at the moment at which the
objects of this class are created: Rectangle smallRectangle (5,3);
Constructors cannot be called explicitly as if they were regular member functions. They are only executed
when a new object of that class is created.
The destructor fulfills the opposite functionality. It is automatically called when an object is destroyed,
either because its scope of existence has finished (for example, if it was defined as a local object within a
function and the function ends) or because it is an object dynamically assigned and it is released using the
operator delete.
The destructor must have the same name as the class, but preceded with a tilde sign (~) and it must also
return no value.
The use of destructors is especially suitable when an object assigns dynamic memory during its lifetime
and at the moment of being destroyed we want to release the memory that the object was allocated.
int main()
{
Rectangle smallRectangle(5,3);
smallRectangle.getArea();
smallREctangle.getPerimeter();
return 0;
}
Rectangle::Rectangle(int l, int b){
length = l;
breadth = b;
}
Rectangle::~Rectangle(){
delete length;
delete breadth;
}
Observe, that we included the body of the getArea() and getPerimeter() methods in the class
declaration. In fact we could also include the body of the constructor and destructor in the class
declaration. It becomes a class definition.
OBJECTIVES
1 Students should understand the concepts of Friendship and Inheritance in OOP
2 They should also be able to write simple programs that uses inheritance
Friend functions
In principle, private and protected members of a class cannot be accessed from outside the same class in
which they are declared. However, this rule does not affect friends. Friends are functions or classes
declared as such. If we want to declare an external function as friend of a class, we do it by declaring a
prototype of this external function within the class, and preceding it with the keyword friend:
// friend functions
#include <iostream>
using namespace std;
class Rectangle {
int width, height;
public:
void set_values (int a, int b) {
width = a;
height = b;
}
int area () {return (width * height);}
friend Rectangle duplicate(Rectangle);
};
The duplicate function is a friend of Rectangle. From within that function we have been able to access
the members width and height of different objects of type Rectangle, which are private members.
Notice that neither in the declaration of duplicate() nor in its later use in main() have we
considered duplicate a member of class Rectangle. It isn't! It simply has access to its private and
protected members without being a member.
Generally, the use of friend functions is out of an object-oriented programming methodology, so
whenever possible it is better to use members of the same class to perform operations with them.
Friend class
Just as we have the possibility to define a friend function, we can also define a class as friend of another
one, granting that first class access to the protected and private members of the second one.
// friend class
#include <iostream>
using namespace std;
class Square;
class Rectangle {
int width, height;
public:
int area (){return (width * height);}
void convert (Square a);
};
class Square {
private:
int side;
public:
void set_side(int a){side=a;}
friend class Rectangle;
};
void CRectangle::convert(Square a) {
width = a.side;
height = a.side;
}
int main () {
Square sqr;
Rectangle rect;
sqr.set_side(4);
rect.convert(sqr);
cout << rect.area();
return 0;
}
In this example, we have declared Rectangle as a friend of Square so that Rectangle member
functions could have access to the protected and private members of Square, precisely the side,
You may also see something new at the beginning of the program: an empty class declaration
class Square;
This is necessary because within the declaration of Rectangle we referred to Square (as a parameter
in convert()). The definition of Square is included later, so if we did not include a previous empty
declaration for Square this class would not be visible from within the definition of Rectangle.
Friendships is not implicitly mutual: it must be explicitly specified. If A declares B as friend, it does not
imply that B sees A as friend too. A can access the private and protected members of B, but B cannot
access the private and protected members of A, except B declares A as friend too. When both declare
each other as friends, we have mutual friendship. Rectangle was declared as friend in Square, but
Square was not declared as friend in Rectangle. Rectangle objects can access the private member
of Square but not the other way round.
Another property of friendships is that they are not transitive: if A is a mutual friend of B and B is a
mutual friend of C, it does not imply that A is a mutual friend of C. Every friendship must be explicitly
declared.
Where derived_class_name is the name of the derived class and base_class_name is the name
of the parent class which it is based. The public access specifier may be replaced by any one of the
other access specifiers protected and private.
//parent class
#include <iostream>
using namespace std;
class Polygon {
protected:
int width, height;
public:
void set_values (int a, int b){ width=a; height=b;}
};
int main() {
Rectangle rect;
Triangle trgl;
rect.set_values(4,5);
trgl.set_values (4,5);
cout << rect.area() << endl;
cout << trgl.area() << endl;
return 0;
}
The objects of the classes Rectangle and Triangle each contain members inherited from Polygon.
These are: width, height and set_values().
The protected access specifier is similar to private. Its only difference occurs in fact with
inheritance. When a class inherits from another one, the members of the derived class can access the
protected members inherited from the base class, but not its private members. Since we wanted width
and height to be accessible from members of the derived classes Rectangle and Triangle and not
only by members of Polygon, we have used protected access instead of private.
We can summarize the different access types according to who can access them in the following way:
Access specifier
Accessing from public protected private
Members of the same class yes yes yes
Members of derived classes yes yes no
Others yes no no
Where "others" represent any access from outside the class, such as from main(), from another class or
from a function.
In our example, the members inherited by Rectangle and Triangle have the same access
permissions as they had in their base class Polygon:
Polygon::width // protected access
Rectangle::width // protected access
Triangle::width // protected access
Polygon::set_values() // public access
Rectangle::set_values() // public access
Triangle::set_values() // public access
This is because we have used the public keyword to define the inheritance relationship on each of the
derived classes:
class Rectangle: public Polygon { ... }
This public keyword after the colon (:) denotes the maximum access level for all the members
inherited from the parent class . Since public is the most accessible level, by specifying this keyword, the
derived class will inherit all the members with the same levels they had in the base class.
If we specify a more restrictive access level like protected, all public members of the base class are
inherited as protected in the derived class. Whereas if we specify the most restricting of all access levels :
private, all the base class members with protected and public access are inherited as private.
That maximum access level only affects the inherited members. If we do not explicitly specify any access
level for the inheritance, the compiler assumes private.
Multiple inheritance
In C++ it is perfectly possible that a class inherits members from more than one class. This is done by
simply separating the different base classes with commas in the derived class declaration. For example, if
we have the following classes Staff, Student, StaffStudent. Since a staff-student is both a Staff and
a Student, our declaration will be like
class StaffStudent: public Staff, public Student;
OBJECTIVES
1 Students should be able to use function overloading as a concept of polymorphism.
2 They should also be able to use operator overloading as concept of polymorphism.
3 They should be able to perform class level polymorphism.
INTRODUCTION
Polymorphism is the ability to use an operator or method in different ways. Polymorphism gives different
meanings or functions to the operators or methods. Poly, referring to many, signifies the many uses of
these operators and methods. A single method usage or an operator functioning in many ways can be
called polymorphism. Polymorphism refers to codes, operations or objects that behave differently in
different contexts.
Function Overloading
#include<iostream>
using namespace std;
class employee{
public:
int week;
int year;
double calculate(double salary){
return(salary*week);
}
int calculate(int salary){
return(salary*week*year);
}
employee(int week1){
week=week1;
}
employee(int week1,int year1){
week=week1;
year=year1;
}
};
int main(){
int sal;
double sal2;
employee emp1(10);
employee emp2(10,3);
cout << "Enter the no years for first employee" << endl;
cin >> emp1.year;
cout<<endl<<"Enter the salary per week for first employee" << endl;
cin >> sal;
cout << "The total salary of first employee is: "
<< emp1.calculate(sal) << endl;
cout << endl << "Enter the salary per week for second employee is: "
<< endl;
cin >> sal2;
cout << "The total salary of second employee is for one year: "
<< emp2.calculate(sal2) << endl;
return(0);
}
Operator Overloading
The task below demonstrates the use of operator concept in C++.
i. Enter the codes into C++ source files
ii. Give it a name OverExample
iii. Compile the program, if no errors
iv. Execute it.
#include<iostream>
using namespace std;
class rectangle{
public:
int length;
int breadth;
rectangle(int length1,int breadth1){
length=length1;
breadth=breadth1;
}
int operator+(rectangle r1){
return(r1.length+length);
}
};
int main ()
{
rectangle r1(10,20);
rectangle r2(40,60);
int len;
len=r1+r2;
cout << "The total length of the two rectangles is : " << len
<< endl;
return(0);
}
The program consists of operator + function which is overloaded. The + operator is used to perform addition of the
length of the objects. The statements
int operator+(rectangle r1){
return(r1.length+length);
}
Class Level Polymorphism
C++ polymorphism means that a call to a member function will cause a different function to be executed
depending on the type of object that invokes the function.
Consider the following example where a base class has been derived by other two classes
int area () {
cout << "Rectangle class area :" << endl;
return (width * height);
}
};
int area () {
cout << "Triangle class area :" << endl;
return (width * height / 2);
}
};
(Source:www.tutorialspoint.com/cplusplus/cpp_polymorphism.htm)
OBJECTIVES
1. Students should know to how write C++ program using Arrays.
2. Students should learn to write C++ program using Pointer.
INTRODUCTION
An array is a series of elements of the same type placed in contiguous memory locations that can be
individually referenced by adding an index to a unique identifier.
The task below demonstrates the use of Array in C++.
i. Enter the codes into C++ source files
ii. Give it a name ArrayExample
iii. Compile the program, if no errors
iv. Execute it.
// arrays example
#include <iostream>
using namespace std;
int main(){
const int NumberOfItems = 5;
double distance[NumberOfItems] = {44.14,720.52,96.08,468.78, 6.28};
cout<<"Distance 1:"<<distance[0]<<endl;
cout<<"Distance 2:"<<distance[1]<<endl;
cout<<"Distance 3:"<<distance[2]<<endl;
cout<<"Distance 4:"<<distance[3]<<endl;
cout<<"Distance 5:"<<distance[4]<<endl;
cout<<"Distance 6:"<<distance[5]<<endl;
cout<<"Distance 7:"<<distance[6]<<endl;
cout<<"Distance 8:"<<distance[7]<<endl;
return 0;
}
? DO YOU KNOW?
// arrays example
#include <iostream>
using namespace std;
int Dajj []= 5;
int n, result=0;
int main ()
{
for ( n=0 ; n<5 ; n++ )
{
result += Ade[n];
}
cout << result<<endl;
return 0;
}
Pointer Operators
There are two important pointer operators, ‘*’ and ‘&’. The ‘&’ is a unary operator. The unary operator
returns the address of the memory where a variable is located. For example,
int x*;
int c;
x=&c;
variable x is the pointer of the type integer and it points to location of the variable c. When the statement
x=&c;
is executed, ‘&’ operator returns the memory address of the variable c and as a result x will point to the
memory location of variable c.
The general form of declaring pointer is:-
type *variable_name;
type is the base type of the pointer and variable_name is the name of the variable of the pointer. For
example,
int *x;
The task in the next page demonstrates the use of Pointer in C++.
i Enter the codes into C++ source files
ii. Give it a name PointerExample
iii. Compile the program, if no errors
iv. Execute it.
#include<iostream>
using namespace std;
int main (){
int *x;
int *p,*q;
int c=100,a;
x=&c;
p=x+2;
q=x-2;
a=p-q;
cout << "The address of x : " << x << endl;
cout << "The address of p after incrementing x by 2 : " << p << endl;
cout << "The address of q after derementing x by 2 : " << q << endl;
cout << " The no of elements between p and q :" << a << endl;
return(0);}
int main ()
{
int firstvalue, secondvalue;
mypointer = firstvalue;
*mypointer = 10;
mypointer = secondvalue;
*mypointer = 20
cout << " " << << endl;
cout << " << endl;
return 0;
}
3. Give the annotation of the corrected program above
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________
________________________________________________________________________________________________________________