Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

KCA University

Nairobi, Kenya

BIT 2108: OBJECT ORIENTED PROGRAMMING


Prepared By:
Linus Aloo
E-mail: linusaloo88@gmail.com
Phone: 0754188380
References
1. E. Balagurusamy, “Object-Oriented Programming with C++,” Tata McGraw
Hill, 2008.
2. R. Lafore, “Object-Oriented Programming in C++, SAMS Publishing, Fourth
Edition, 2002.
3. S A Bhave Patekav, “Object-oriented Programming,” Pearson education, 2004
4. S.B.Lippman and J.Lajoie, “Object Oriented Programming in C++, 3rd Edition,
Pearson Education, 2008.

10/21/2021 BIT 2108 1


Week 4: Chapter 3: OBJECT ORIENTED PROGRAMMING IN A SELECTED
LANGUAGE

3.0. Learning Objectives


At the end of this submodule unit, the learner should be able to
1. Explain key Concepts and terminology; abstraction, encapsulation,
Inheritance, polymorphism, classes, objects, methods, messages.
2. Demonstrate an understanding of Object Oriented concepts.
3. Define a token
4. Declare and use a variable
5. Define and use various data types in C++
6. Define and use constants
7. Apply Object Oriented concepts using a C++
10/21/2021 BIT 2108 2
Week 4: Chapter 3: OBJECT ORIENTED PROGRAMMING IN A
SELECTED LANGUAGE
3.1. Basics of C++
 C ++ is an object oriented programming language, developed by Jarney Stroustrup at AT & T Bell lab, USA in early eighties.
 C ++ was developed from c and simula 67 language.
3.1.1. C++ Comments:
 C++ introduces a new comment symbol //(double slash).
 Comments start with a double slash symbol and terminate at the end of line.
 The double slash comment is basically a single line comment. Multi line comments can be written as follows:

// this is an example of
// c++ program
// thank you

 The c comment symbols /* ….*/ are still valid and more suitable for multi line comments.
/* this is an example of c++ program */

10/21/2021 BIT 2108 3


Week 4: Chapter 3: OBJECT ORIENTED PROGRAMMING IN A
SELECTED LANGUAGE
3.1. Basics of C++
3.1.2. Output Operator:
 The statement cout <<”Hello, world” displays the string within
quotes on the screen.
 The identifier cout can be used to display individual characters,
strings and even numbers.
 It is a predefined object that corresponds to the standard output
stream.
 Stream just refers to a flow of data, normally to the screen display.
 The cout object, whose properties are defined in iostream.h
represents that stream.
 The insertion operator << also called the ‘put to’ operator directs the
information on its right to the object on its left as shown in Fig.3.1. Fig.3.1. Output using insertion operator
10/21/2021 BIT 2108 4
Week 4: Chapter 3: OBJECT ORIENTED PROGRAMMING IN A
SELECTED LANGUAGE
3.1. Basics of C++
3.1.3. Return Statement:
 In C++ main ( ) returns an integer type value to the operating system.
 Therefore every main ( ) in C++ should end with a return (0) statement, otherwise a warning or an error might
occur.
3.1.4. Input Operator:
The statement cin>> number 1;

is an input statement and causes the program to wait for the user to type
in a number.
 The number keyed in is placed in the variable number1. The
identifier cin is a predefined object in C++ that corresponds to the
standard input stream. Here this stream represents the key board.
 The operator >> is known as get from operator. It extracts value from
Fig.3.2. Output using insertion operator
the keyboard and assigns it to the variable on its right (Fig.3.2).
10/21/2021 BIT 2108 5
Week 4: Chapter 3: OBJECT ORIENTED PROGRAMMING IN A
SELECTED LANGUAGE
3.1. Basics of C++
// my first program in C++
3.1.5. Cascading of I/O Operator:
 This is a comment line.
cout<<”sum=”<<sum<<”\n”;
cout<<”sum=”<<sum<<”\n”<<”average=”<<average<<”\n”;
cin>>number1>>number2;  All lines beginning with two slash signs (//) are
3.1.6. Structure of a Program considered comments and do not have any effect on the
Consider the following program: behavior of the program.
// my first program in C++

#include <iostream> #include <iostream>


using namespace std;
 Lines beginning with a hash sign (#) are directives for the
int main ()
{ preprocessor.
cout << "Hello World!";
return 0;
}  They are not regular code lines with expressions but
Output:-Hello World! indications for the compiler's preprocessor.
We are going to look line by line at the code we have just written:  In this case the directive #include<iostream> tells the
preprocessor to include the iostream standard file.
10/21/2021 BIT 2108 6
Week 4: Chapter 3: OBJECT ORIENTED PROGRAMMING IN A
SELECTED LANGUAGE
3.1. Basics of C++

3.1.6. Structure of a Program


 Some old versions of C++ use a header file called iostream.h. This is one of the changes that came
with ANSI C++.
 NB: We should use iostream.h if the compiler does not support ANSI C++ features.
 The header file iostream should be included at the beginning of all programs that use
input/output statements.
Table 3.1 and 3.2 provide lists of C++ standard library header files that may be needed in C++
programs.
The header files having .h extension are “old style” files, which should be used with old compilers.
Table 3.1 also gives the version of these files that should be used with the ANSI standard compilers.

10/21/2021 BIT 2108 7


Week 4: Chapter 3: OBJECT ORIENTED PROGRAMMING IN A
SELECTED LANGUAGE
3.1. Basics of C++
Table 3.2 New header files included in ANSI C++
3.1.6. Structure of a Program
Table 3.1 Commonly used old-style header files

10/21/2021 BIT 2108 8


Week 4: Chapter 3: OBJECT ORIENTED PROGRAMMING IN A
SELECTED LANGUAGE
3.1. Basics of C++
3.1.6. Structure of a Program

using namespace std;


 All the elements of the standard C++ library are declared within what is called a namespace, the
namespace with the name std.
 So in order to access its functionality we declare with this expression that we will be using these
entities.
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.

10/21/2021 BIT 2108 9


Week 4: Chapter 3: OBJECT ORIENTED PROGRAMMING IN A
SELECTED LANGUAGE
3.1. Basics of C++
3.1.6. Structure of a Program

cout << "Hello World!";


 This line is a C++ statement. It performs the only action that generates a visible effect in our first program.
 cout represents the standard output stream in C++, and the meaning of the entire statement is to insert a sequence of
characters (in this case the Hello World sequence of characters) into the standard output stream (which usually is the
screen).
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.

10/21/2021 BIT 2108 10


Week 4: Chapter 3: OBJECT ORIENTED PROGRAMMING IN A
SELECTED LANGUAGE
3.1. Basics of C++
3.1.6. Structure of a Program

#include <iostream>
Program 3.1: Average of two numbers using namespace std;

 Assume that we would like to read two int main()


{
numbers from the keyboard and display float number1, number2,
sum, average;
their average on the screen. C++ cout<< “Enter two numbers: ” ; // prompt

statements required to achieve this is cin >> number1; // Reads numbers


cin >> number2; // from keyboard
shown in Program 3.1. sum = number1 + number2;
average = sum/2;
}
cout << “Sum = ” << sum << “\n” ;
cout << “Average = ” << average << “\n” ;
return 0;
}

10/21/2021 BIT 2108 11


Week 4: Chapter 3: OBJECT ORIENTED PROGRAMMING IN A
SELECTED LANGUAGE

3.2. Structure of C++ Program

 As is shown in Fig.3.2, a typical C++


program would contain four sections:

 Include files
 Class declaration
 Class functions, definition
 Main function program

Fig.3.2 Structure of a C++ Program

10/21/2021 BIT 2108 12


Week 4: Chapter 3: OBJECT ORIENTED PROGRAMMING IN A
SELECTED LANGUAGE
C++ KEYWORDS:
3.3.1. Keywords:
 The keywords implement
3.3. Tokens
specific C++ language
 The smallest individual
feature.
units in program are
 They are explicitly reserved
known as tokens. C++
identifiers and cannot be used
has the following tokens.
as names for the program
i. Keywords
variables or other user defined
ii. Identifiers
program elements.
iii. Constants
 The keywords not found in
iv. Strings
ANSI C are shown in red
v. Operators
letter.

10/21/2021 BIT 2108 13


Week 4: Chapter 3: OBJECT ORIENTED PROGRAMMING IN A
SELECTED LANGUAGE

3.3.2. Identifiers
 Identifiers refers to the name of variable, functions, array, class etc. created by programmer.
 Each language has its own rule for naming the identifiers.
 The following rules are common for both C and C++.

1. Only alphabetic chars, digits and underscore are permitted.


2. The name can’t start with a digit.
3. Upper case and lower case letters are distinct.
4. A declared keyword can’t be used as a variable name.

 In ANSI C the maximum length of a variable is 32 chars but in c++, there is no bar.

10/21/2021 BIT 2108 14


Week 4: Chapter 3: OBJECT ORIENTED PROGRAMMING IN A
SELECTED LANGUAGE
3.4. BASIC DATA TYPES IN C++
 With the exception of void, the basic
3.4.1. The basic data types in C++.
datatypes may have several modifiers
Fig. 3.3 shows the basic data types in C++.
preceding them to serve the needs of various
situations.
 The modifiers signed, unsigned, long and
short may be applied to character and integer
basic data types.
 However, the modifier long may also be
applied to double.
 Data types in C++ can be classified under

Fig.3.3 The basic data types in C++.


various categories.

10/21/2021 BIT 2108 15


Week 4: Chapter 3: OBJECT ORIENTED PROGRAMMING IN A
SELECTED LANGUAGE
3.4. BASIC DATA TYPES IN C++
3.4.1. The basic data types in C++.

3.4.2. User Defined Data Types


1. Structures and Classes
 When using C++ in the case of object-oriented
programming, C++ also permits us to define another
user defined data type known as class, which can be
used, just like any other basic data type to declare a
variable.
 The class variables are known as objects.

10/21/2021 BIT 2108 16


Week 4: Chapter 3: OBJECT ORIENTED PROGRAMMING IN A
SELECTED LANGUAGE
3.4. BASIC DATA TYPES IN C++
3.4.1. The basic data types in C++.
2. Enumerated Data Type.
 An enumerated data type is another user-defined type, which provides a way for attaching names to
number, there by increasing comprehensibility of the code.
 The enum keyword automatically enumerates a list of words by assigning them values 0, 1, 2 and so on.
Example:
enum shape { circle,square,triangle}
enum colour{red,blue,green,yellow}
enum position {off, on}

10/21/2021 BIT 2108 17


Week 4: Chapter 3: OBJECT ORIENTED PROGRAMMING IN A
SELECTED LANGUAGE
3.4. BASIC DATA TYPES IN C++
Here, age is a variable of the int data type, and we have
3.5. C++ Variables and Literals
assigned an integer value 14 to it.

a) Variables
 In programming, a variable is a container Note: The int data type suggests that the variable can
(storage area) to hold data. only hold integers. Similarly, we can use the double data

 To indicate the storage area, each variable type if we have to store decimals and exponentials.
should be given a unique name (identifier).
For example,
 The value of a variable can be changed, hence the
int age = 14;
name variable.
int age = 14; // age is 14
age = 17; // age is 17
10/21/2021 BIT 2108 18
Week 4: Chapter 3: OBJECT ORIENTED PROGRAMMING IN A
SELECTED LANGUAGE
3.4. BASIC DATA TYPES IN C++

3.5. C++ Variables and Literals


Rules for naming a variable
•A variable name can only have alphabets, numbers, and the underscore _.
•A variable name cannot begin with a number.
•Variable names should not begin with an uppercase character.
•A variable name cannot be a keyword. For example, int is a keyword that is used to
denote integers.
•A variable name can start with an underscore. However, it's not considered a good
practice.
Note: We should try to give meaningful names to variables. For example, first_name is a
better variable name than fn.
10/21/2021 BIT 2108 19
Week 4: Chapter 3: OBJECT ORIENTED PROGRAMMING IN A
SELECTED LANGUAGE
3.4. BASIC DATA TYPES IN C++ Reference Variables.
3.5. C++ Variables and Literals  C++interfaces a new kind of variable known as the reference variable.

Example on declaration of variables:  A references variable provides an alternative name for a previously defined
variable.
main( )  For example, if we refer to the variable total, then sum and total can be used
{
float x,average; interchangeably to represent the variable.
float sum=0;  A reference variable is created as follows:
for(int i=1;i<5;i++)  Syntax: Datatype & reference –name=variable name;
{
cin>>x; Example:
sum=sum+x float total=1500;
} float &sum=total;
float average;
average=sum/x;  Here sum is the alternative name for variables total; both the variables refer to the
cout<<average; same data object in the memory.
}

10/21/2021 BIT 2108 20


Week 4: Chapter 3: OBJECT ORIENTED PROGRAMMING IN A
SELECTED LANGUAGE
3.4. BASIC DATA TYPES IN C++

3.5. C++ Variables and Literals b) C++ Literals

 A reference variable must be  Literals are data used for representing fixed values. They can be used directly in
initialized at the time of the code. For example: 1, 2.5, 'c' etc.
declaration.  Here, 1, 2.5 and 'c' are literals. Why? You cannot assign different values to these
 Note that C++ assigns additional
terms.
meaning to the symbol & here &
The following is a list of different literals in C++ programming.
is not an address operator.
 The notation float & means 1. Integers
reference to float.  An integer is a numeric literal (associated with numbers) without any fractional
or exponential part. There are three types of integer literals:
Example:
•decimal (base 10)
int n[10];
int &x=n[10]; •octal (base 8)
char &a=’\n’; •hexadecimal (base 16)

10/21/2021 BIT 2108 21


Week 4: Chapter 3: OBJECT ORIENTED PROGRAMMING IN A
SELECTED LANGUAGE
3.4. BASIC DATA TYPES IN C++
b) C++ Literals
3.5. C++ Variables and Literals  In C++ programming, octal starts with a 0, and hexadecimal
 A reference variable must be starts with a 0x. For example:
initialized at the time of
Decimal: 0, -9, 22 etc
declaration. Octal: 021, 077, 033 etc
 Note that C++ assigns additional Hexadecimal:Literals
0x7f, 0x2a, 0x521 etc
2. Floating-point
meaning to the symbol & here &
is not an address operator. A floating-point literal is a numeric literal that has either a fractional
 The notation float & means
form or an exponent form. For example:
reference to float.
 -2.0
Example:  0.0000234
int n[10];
int &x=n[10];  -0.22E-5
char &a=’\n’; Note: E-5 = 10-5

10/21/2021 BIT 2108 22


Week 4: Chapter 3: OBJECT ORIENTED PROGRAMMING IN A
SELECTED LANGUAGE
3.4. BASIC DATA TYPES IN C++ In order to use these characters, escape sequences are
used (Table 3.3).
3.5. C++ Variables and Literals Table 3.3. Escape Sequences
Escape Sequences Characters
3. Characters
\b Backspace
A character literal is created by enclosing a
\f Form feed

single character inside single quotation \n Newline

marks. For example: 'a', 'm', 'F', '2', '}' etc. \r Return

\t Horizontal tab
4. Escape Sequences
\v Vertical tab
Sometimes, it is necessary to use characters
\\ Backslash
that cannot be typed or has special meaning \' Single quotation mark

in C++ programming. For example, newline \" Double quotation mark

(enter), tab, question mark, etc. \? Question mark

\0 Null Character

10/21/2021 BIT 2108 23


Week 4: Chapter 3: OBJECT ORIENTED PROGRAMMING IN A
SELECTED LANGUAGE
3.4. BASIC DATA TYPES IN C++

3.5. C++ Variables and Literals

5. String Literals

 A string literal is a sequence of characters enclosed in double-quote marks. For example (Table3.4):
Table 3.4. String Literals

"good" string constant

"" null string constant

"" string constant of six white space

"x" string constant having a single character

"Earth is round\n" prints string with a newline

10/21/2021 BIT 2108 24


Week 4: Chapter 3: OBJECT ORIENTED PROGRAMMING IN A
SELECTED LANGUAGE
3.4. BASIC DATA TYPES IN C++

3.5. C++ Variables and Literals

5. String Literals

3.6. Symbolic Constant


There are two ways of creating symbolic constants in c++.
1. Using the Keyword (qualifier) const.
2. Defining a set of integer constants using enum keywords.
 In C++, the program in any way cannot modify any value declared as const.
Here is an example:
const int LIGHT_SPEED = 299792458;LIGHT_SPEED = 2500 // Error! LIGHT_SPEED is
a constant.
Here, we have used the keyword const to declare a constant named LIGHT_SPEED. If we
try to change the value of LIGHT_SPEED, we will get an error.
10/21/2021 BIT 2108 25
Week 4: Chapter 3: OBJECT ORIENTED PROGRAMMING IN A
SELECTED LANGUAGE
3.4. BASIC DATA TYPES IN C++

3.5. C++ Variables and Literals

3.6. Symbolic Constant

 We can use const in a constant expression. Such as

const int size = 10 ;


char name (size) ;
 C++ requires a const to be initialized and the const values are local. If we want to make const value as global then
declare as extern storage class.
Ex:
external const total=100;
 Another method of naming integer constants is as follows:-
enum {x,y,z};]
10/21/2021 BIT 2108 26
Week 4: Chapter 3: OBJECT ORIENTED PROGRAMMING IN A
SELECTED LANGUAGE

3.6. Programming Exercises [ii]. Using const keyword.

Defining symbolic constants Study the program below that uses a constant ,
compile and run it.
[i]. Using #define preprocessor.
Study the program below then compile and run.

10/21/2021 BIT 2108 27


Week 4: Chapter 3: OBJECT ORIENTED PROGRAMMING IN A
SELECTED LANGUAGE

3.7. Revision questions

a) Differentiate between symbolic constant and literal constants


b) Explain why symbolic constants are important
c) Describe any three rules followed when naming a variable.
d) State any five reserved keywords in C++
END OF WEEK 5 LECTURE

10/21/2021 BIT 2108 28

You might also like