[go: up one dir, main page]

0% found this document useful (0 votes)
48 views56 pages

Object Oriented Proramming Notes 1

This document provides an introduction to object oriented programming with C++. It discusses high level languages, procedure oriented programming, and key concepts of object oriented programming including objects, classes, encapsulation, inheritance, polymorphism, and dynamic binding. The document is a course outline for an "Object Oriented Programming with C++" class that will cover these fundamental OOP concepts.

Uploaded by

Young Uther
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views56 pages

Object Oriented Proramming Notes 1

This document provides an introduction to object oriented programming with C++. It discusses high level languages, procedure oriented programming, and key concepts of object oriented programming including objects, classes, encapsulation, inheritance, polymorphism, and dynamic binding. The document is a course outline for an "Object Oriented Programming with C++" class that will cover these fundamental OOP concepts.

Uploaded by

Young Uther
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

COURSE TITLE: OBJECT ORIENTED PROGRAMMING(WITH C++)

COURSE CODE: CS2101


LECTURER : Mr. ARAKA GEOFFREY

Object oriented programming [BCS & BIT] Page 1


Introduction
What is a program
Is a specific set of instructions or operations to be executed to achieve a particular goal.

Programmers write instructions in various programming languages to perform their computation


tasks such as:
i. Machine level Language
ii. Assembly level Language
iii. High level Language

Machine level Language :


Machine code or machine language is a set of instructions executed directly by a computer's
central processing unit (CPU). Each instruction performs a very specific task, such as a load, a
jump, or an ALU operation on a unit of data in a CPU register or memory. Every program
directly executed by a CPU is made up of a series of such instructions.
Assembly level Language :
An assembly language is a low-level programming language for a computer, microcontroller, or
other programmable device, in which each statement corresponds to a single machine code
instruction. Each assembly language is specific to a particular computer architecture.
Assembly language is converted into executable machine code by a utility program referred to as
an assembler; the conversion process is referred to as assembly, or assembling the code.
High level Language : High-level language is any programming language that enables
development of a program in much simpler programming context and is generally independent
of the computer's hardware architecture. High-level language has a higher level of abstraction
from the computer, and focuses more on the programming logic rather than the underlying
hardware components such as memory addressing and register utilization.
The first high-level programming languages were designed in the 1950s. Now there are dozens
of different languages, including Ada , Algol, BASIC, COBOL, C, C++, JAVA, FORTRAN,
LISP, Pascal, and Prolog. Such languages are considered high-level because they are closer to
human languages and farther from machine languages. In contrast, assembly languages are
considered low level because they are very close to machine languages.
The high-level programming languages are broadly categorized into two categories:

 Procedure oriented programming (POP) language.


 Object oriented programming (OOP) language.

Object oriented programming [BCS & BIT] Page 2


Procedure Oriented Programming Language

 In the procedure oriented approach, the problem is viewed as sequence of things to be done such
as reading , calculation and printing. Procedure oriented programming basically consist of
writing a list of instruction or actions for the computer to follow and organizing these instruction
into groups known as functions. Examples are
 C
 Fortran
 Pascal
 COBOL
 BASIC
 ALGOL

The disadvantage of the procedure oriented programming languages is:

1. Global data access

2. It does not model real world problem very well

3. No data hiding

Object oriented programming [BCS & BIT] Page 3


Characteristics of procedure oriented programming:

1. Emphasis is on doing things(algorithm)

2. Large programs are divided into smaller programs known as functions.

3. Most of the functions share global data

4. Data move openly around the system from function to function

5. Function transforms data from one form to another.

6. Employs top-down approach in program design

Object Oriented Programing


Object-oriented programming (OOP) is a programming paradigm that uses objects and their
interactions to design applications and computer programs.
OOP is based on the idea that everything in a program is an object, and that objects can interact
with each other by sending and receiving messages.

Features of the Object Oriented programming


1. Emphasis is on doing rather than procedure.
2. programs are divided into what are known as objects.
3. Data structures are designed such that they characterize the objects.
4. Functions that operate on the data of an object are tied together in the data structure.

Object oriented programming [BCS & BIT] Page 4


5. Data is hidden and can‘t be accessed by external functions.
6. Objects may communicate with each other through functions.
7. New data and functions can be easily added.
8. Follows bottom-up approach in program design

BASIC CONCEPTS OF OBJECT ORIENTED PROGRAMMING


Principles( or features) of object oriented programming/The OPPs concept
1. Objects
2. Classes
3. Data abstraction and encapsulation
4. Inheritance
5. Polymorphism
6. Dynamic binding
7. Message passing

Objects
Are the basic run-time entities in an object-oriented system. They may represent a person, a
place, a bank account, a table of data or any item that the program must handle. The fundamental
idea behind object oriented approach is to combine both data and function into a single unit and
these units are called objects.
The term objects means a combination of data and program that represent some real word entity.
For example: consider an example named JOHN; JOHN is 25 years old and his salary is 2500.
The JOHN may be represented in a computer program as an object. The data part of the object
would be (name: John, age: 25, salary: 2500)
The program part of the object may be collection of programs (retrive of data, change age,
change of salary). In the John object the name, age and salary are called attributes of the object.

Object oriented programming [BCS & BIT] Page 5


CLASS:
A group of objects that share common properties for data part and some program part are
collectively called as class. In C ++ a class is a new data type that contains member variables and
member functions that operate on the variables
DATA ABSTRACTION :
Abstraction refers to the act of representing essential features without including the back ground
details or explanations.
Data abstraction refers to providing only essential information about the data to the outside
world, hiding the background details or implementation. We can implement Abstraction in
C++ using classes. The class helps us to group data members and member functions using
available access specifiers. A Class can decide which data member will be visible to the
outside world and which is not.
DATA ENCAPSULATION: The wrapping up of data and function into a single unit (called
class) is known as encapsulation. The data is not accessible to the outside world and only those
functions which are wrapped in the class can access it. These functions provide the interface
between the objects data and the program.
INHERITENCE: Inheritance is the process by which objects of one class acquire the properties
of another class. In the concept of inheritance provides the idea of reusablity. This mean that we
can add additional features to an existing class without modifying it. This is possible by
designing a new class which will have the combined features of both the classes.
POLYMORPHISIM: Polymorphism means the ability to take more than one form. An
operation may exhibit different instance. The behaviour depends upon the type of data used in
the operation. A language feature that allows a function or operator to be given more than one
definition. The types of the arguments with which the function or operator is called determines
which definition will be used.
Overloading may be operator overloading or function overloading.
It is able to express the operation of addition by a single operator say ‗+‘. When this is possible
you use the expression x + y to denote the sum of x and y, for many different types of x and y;

Object oriented programming [BCS & BIT] Page 6


integers, float and complex no. You can even define the + operation for two strings to mean the
concatenation of the strings.
Function overloading is a feature of object-oriented programming where two or more functions
can have the same name but different parameters. When a function name is overloaded with
different jobs it is called Function Overloading.
DYNAMIC BINDING : Binding refers to the linking of a procedure call to the code to be
executed in response to the call. Dynamic binding means the code associated with a given
procedure call is not known until the time of the call at run-time.
dynamic binding is delaying the selection or choice of which function to run until its runtime. It
is associated with a polymorphic reference depends upon the dynamic type of that reference.
MESSAGE PASSING : An object oriented program consists of a set of objects that
communicate with each other. A message for an object is a request for execution of a procedure
and therefore will invoke a function (procedure) in the receiving object that generates the desired
result. Message passing involves specifying the name of the object, the name of the function
(message) and information to be sent.

BENEFITS OF OOP:
Oop offers several benefits to both the program designer and the user. Object-oriented
contributes to the solution of many problems associated with the development and quality of
software products. The principal advantages are :
1. Through inheritance we can eliminate redundant code and extend the use of existing classes.
2. We can build programs from the standard working modules that communicate with one
another, rather than having to start writing the code from scratch. This leads to saving of
development time and higher productivity.
3. This principle of data hiding helps the programmer to build secure programs that can‘t be
invaded by code in other parts of the program.
4. It is possible to have multiple instances of an object to co-exist without any interference.
5. It is easy to partition the work in a project based on objects.
6. Object-oriented systems can be easily upgraded from small to large systems.

Object oriented programming [BCS & BIT] Page 7


7. Message passing techniques for communication between objects makes the interface
description with external systems much simpler.
8. Software complexity can be easily managed.

APPLICATION OF OOP:
The most popular application of oops up to now, has been in the area of user interface design
such as windows. There are hundreds of windowing systems developed using oop techniques.
Real business systems are often much more complex and contain many more objects with
complicated attributes and methods. Oop is useful in this type of applications because it can
simplify a complex problem. The promising areas for application of oop includes.
1. Real – Time systems.
RTS are considered to be systems whose behavior depends on the time elapsed, since
they start processing data entries until the outputs are known. One of the most important
features is that the response time of these systems must be predictable and limited.
2. Simulation and modeling
is the use of a physical or logical representation of a given system to generate data and
help determine decisions or make predictions about the system

3. Object oriented databases.


Is a database system that can work with complex data objects — that is, objects that
mirror those used in object-oriented programming languages
4. Hypertext,hypermedia and expertext.
Hypertext, hypermedia, and expertext are all related concepts,but have different
meanings.

Hypertext, hypermedia, and expertext are all related concepts, but they have different nuances.

Hypertext is a system of interlinking nodes of text. Nodes can be anything from a single word to
a paragraph or even a whole document. The nodes are linked together using hyperlinks, which
are typically underlined or blue words or phrases

Hypermedia is an extension of hypertext that includes non-text elements, such as images, audio,
video, and animations
Expertext is a type of hypermedia that is designed to provide users with expert knowledge on a
particular topic. Expertext systems are used in a variety of settings, including education, training,
and customer support.
5. Al and expert systems.
6. Neural networks and parallel programming.
7. Dicision support and office automation systems.

Object oriented programming [BCS & BIT] Page 8


8. CIM / CAM / CAD system.

BASIC STRUCTURE OF C++ LANGUAGE :


The program written in C++ language follows this basic structure. The sequence of sections
should be as they are in the basic structure.
1. Documentation section
2. Linking section
3. Definition section
4. Global declaration section & class declarations
5.Member function definition
6. Main function section main()
{
Declaration section Executable section
}
1. DOCUMENTATION SECTION : comes first and is used to document the use of logic or
reasons in your program. It can be used to write the program's objective, developer and logic
details. The documentation is done in C language with /* and */ . Whatever is written between
these two are called comments.
2. LINKING SECTION : This section tells the compiler to link the certain occurrences of
keywords or functions in your program to the header files specified in this section. e.g. #include
using namespace std; - directive causes the preprocessor to add the contents of the iostream file
to the program. It contains declarations for cout and cin. cout is a predefined object that
represents the standard output stream. The operator << is an insertion operator, causes the string
in double quotes to be displayed on the screen
The statement cin>>n; is an input statement and causes the program to wait for the user to type
in a number. The number keyed is placed on the variable ―n‖. The identifier cin is a predefined
object in C++ that corresponds to the standard input stream. The operator >> is known as
extraction operator. It extracts the value from the keyboard and assigns it to the value variable on
its right.
3. DEFINITION SECTION : It is used to declare some constants and assign them some value.
e.g. #define MAX 25 Here #define is a compiler directive which tells the compiler whenever
MAX is found in the program replace it with 25.
4. GLOBAL DECLARATION SECTION : Here the variables and class definitions which are
used throughout the program (including main and other functions) are declared so as to make

Object oriented programming [BCS & BIT] Page 9


them global(i.e accessible to all parts of program). A CLASS is a collection of data and functions
that act or manipulate the data. The data components of a class are called data members and
function components of a class are called member functions. A class can also termed as a blue
print or prototype that defines the variable or functions common to all objects of certain kind. It
is a user defined data type
5. SUB PROGRAM OR FUNCTION SECTION : This has all the sub programs or the
functions which our program needs.
void display()
{
cout<<‖C++ is better that C‖;
}
#include iosream.h
using namespace std;
void display()
{
cout<<‘‘ c++ is better than c‘‘;
}
int main()
{
display()
return 0;
}
6. MAIN FUNCTION SECTION : It tells the compiler where to start the execution of a
program from
main()
{
point of execution starts here
}
main function has two sections
1. declaration section : In this the variables and their data types are declared.

Object oriented programming [BCS & BIT] Page 10


2. Executable section or instruction section : This has the part of program which actually
performs the task we need.

7. namespace:
namespace is used to define a scope that could hold global identifiers. ex:-namespace scope for
c++ standard library. classes ,functions and templates are declared within the namespace named
std using namespace std;-->directive can be used.
user defined name space:
syntax for defining name space is
namespace namespace_name
{ //declarations of variables.functions,classes etc...
}

Object oriented programming [BCS & BIT] Page 11


Basics of C++
C ++ is an object oriented programming language, C ++ was developed by Jarney Stroustrup at
AT & T Bell lab, USA in early eighties. C ++ was developed from c and simula 67 language. C
++ was early called ‗C with classes‘

C++ Comments:
C++ introduces a new comment symbol //(double slash). Comments start with a double slash
symbol and terminate at the end of line.
A comment may start anywhere in the line and whatever follows till the end of line is ignored.
Note that there is no closing symbol.
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 */

Output Operator:
The statement cout <<‖Hello, world‖ displayed 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 and the standard Output stream normally flows 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.

Input Operator:
The statement
cin>> number 1;

Object oriented programming [BCS & BIT] Page 12


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 the keyboard
and assigns it to the variable on its right.

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.
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 line with
statements (like the insertion into cout), which were all included within the block.

TOKENS:
The smallest individual units in a program are known as tokens. C++ has the following tokens.

i. Keywords
ii. Identifiers
iii. Constants
iv. Strings
v. Operators

KEYWORDS:
The keywords implement specific C++ language feature. They are explicitly reserved identifiers
and can‘t be used as names for the program variables or other user defined program elements.

Asm double new switch Auto


Else operator template Break enum
Private this Case extern protected
Throw Catch float public try
Char for register typedef Class

Object oriented programming [BCS & BIT] Page 13


Friend return union Const goto
Short unsigned Continue if signed
Virtual Default inline
Sizeof void Delete long struet
While

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. These are user defined names
consisting of sequence of letters and digits
The following rules are common for both C and C++.

 The first character must be an alphabet or underscore.


 It must consist of only letters, digits and underscore.
 Identifiers may have any length but only first 31 characters are significant.
 It must not contain white space or blank space.
 We should not use keywords as identifiers.
 Upper and lower case letters are different.

In ANSI C the maximum length of a variable is 32 chars but in c++ there is no bar.
Example: ab Ab aB AB are treated differently

Examples of valid identifiers: a, x, n, num, SUM, fact, grand_total, sum_of_digits, sum1

Variables
A variable is an identifier which is used to store a value.
Variables are containers for storing data values, like numbers and characters.
variables must be declared before they can be used. This tells the compiler how to work with the
variable and tells the linker how much space needs to be allocated for it.

Rules for declaring and using variables

 A variable name can consist of Capital letters A-Z, lowercase letters a-z digits 0-9, and
the underscore character.
 The first character must be a letter or underscore.
 Blank spaces cannot be used in variable names.
 Special characters like # and $ are not allowed.
 C++ keywords cannot be used as variable names.
 Variable names are case-sensitive.

Object oriented programming [BCS & BIT] Page 14


 A variable name can consist of 31 characters only if we declare a variable more
characters the compiler will ignore after 31 characters.

Variable declaration
A Variable Declaration means that the programmer writes some instructions to tell the compiler
to create the storage in a memory location. The syntax for defining variables is:

Syntax:

data_type variable_name;

data_type variable_name, variable_name, variable_name;

Variables are declared in the above example, but none have been assigned any value. Variables
can be initialized, and initial values can be set along with their declaration.

Syntax:

data_type variable_name = value;

Example:

/* variable declaration and initialization */

int width, height = 5, age = 32;

char letter = 'A';

float area;

double d;

/* actual initialization */

width = 10;

area = 26.5;

Object oriented programming [BCS & BIT] Page 15


Example

#include <iostream>

using namespace std;

int main()

int x = 5;

int y = 2;

int Result;

Result = x * y;

cout << Result;

OPERATORS and EXPRESSIONS C++ :

An operator is a symbol which represents a particular operation that can be performed on data.
An operand is the object on which an operation is performed. By combining the operators and
operands we form an expression.

An expression is a sequence of operands and operators that reduces to a single value.

C operators can be classified as

1. Arithmetic operators

2. Relational operators

3. Logical operators

4. Assignment operators

5. Increment or Decrement operators

6. Conditional operator

7. Bit wise operators

8. unary operator

9. Special operators

Object oriented programming [BCS & BIT] Page 16


C++ has a rich set of operators. All C operators are valid in C++ also.

In addition. C++ introduces some new operators.

1. << insertion operator


2. >> extraction operator
3. : : scope resolution operator
4. : :* pointer to member declarator
5. pointer to member operator .
6. pointer to member operator
7. Delete memory release operator
8. Endl line feed operator
9. New memory allocation operator
10. Setw field width operator

1.Scope Resolution operator:

Scope:-Visibility or availability of a variable in a program is called as scope.

There are two types of scope.

i)Local scope

ii)Global scope

Local scope: visibility of a variable is local to the function in which it is declared.

Global scope: visibility of a variable to all functions of a program Scope resolution operator in
―::‖ . This is used to access global variables if same variables are declared as local and global

Like C,C++ is also a block-structured language. Block -structured language. Blocks and scopes
can be used in constructing programs. We know same variables can be declared in different
blocks because the variables declared in blocks are local to that function. Blocks in C++ are
often nested

Object oriented programming [BCS & BIT] Page 17


Note that declaration in an inner block hides a declaration of the same variable in an outer block
and therefore each declaration of x causes it to refer to a different data object . With in the inner
block the variable x will refer to the data object declared there in.

the global version of a variable can't be accessed from with in the inner block. C++ resolves this
problem by introducing a new operator :: called the scope resolution operator .This can be used
to uncover a hidden variable.

Syntax:
: : variable –name;

Example
#include<iostream>
using namespace std;

int m=10;
main()
{
int m=20;
{
int k=m;
int m=30;
cout<<‖we are in inner block‖;
cout<<"k="<<k<<endl;
cout<<"m="<<m<<endl;
cout<<":: m="<<:: m<<endl;
}
cout<<‖\n we are in outer block \n‖;
cout<<"m="<<m<<endl;
cout<<":: m="<<:: m<<endl;
}

Object oriented programming [BCS & BIT] Page 18


Member Dereferencing operator:-
1. Pointer to a member declarator ::*
This operator is used for declaring a pointer to the member of the class. It is possible to
take the address of a member of a class and assign it to a pointer. The address of a
member can be obtained by applying the operator & to a ―fully qualified‖ class member
name.

A class member pointer can be declared using the operator :: * with the class name. We
can define a pointer to the member m of class ABC as follows :

Syntax for declaration and assignement

Datatype class_name :: *pointer_name;

Assignment

Pointer_name =&class_name ::datamember_name;

Both declaration and assignment can be done on a single ststement

Datatype class_name :: *pointer_name=&class_name ::datamember_name;

example
2. Pointer to member operator ->*,->
Let us assume that ―A‖ is an object of ―ABC‖ declared in a main function . We can
access ―m‖ using the pointer ip as follows.
#include<iostream>
using namespace std;
class sample
{
public:
int x;
void display()
{
cout<<"x="<<x<<endl;
}
};
int main()

Object oriented programming [BCS & BIT] Page 19


{
sample s;
sample *ptr;
//object
int sample::*f=&sample::x;
s.x=10;
ptr=&s;
cout<<ptr->*f;
ptr->display();
}

3. Pointer to member operator .*


Let us assume that ―A‖ is an object of ―ABC‖ declared in a main function . We can
access ―m‖ using the pointer ip as follows.
//pointer to member operator
#include<iostream>
using namespace std;
class ABC
{
public:
int x;
};
int main()
{
ABC A; //object
int ABC::*ip; //pointer declaration
ip=&ABC::x; //pointer initialization
A.*ip=10; //value initialization
cout<<A.*ip;
}
Output:10

CONSTANTS:
Constants refer to values that do not change during the execution of a program. Constants can be
divided into two major categories:

1.Primary constants:

a)Numeric constants

 Integer constants.
 Floating-point (real) constants.

b)Character constants

Object oriented programming [BCS & BIT] Page 20


 Single character constants
 String constants

2.Secondary constants:

 Enumeration constants.
 Symbolic constants.
 Arrays, unions, etc.

Rules for declaring constants:

 1.Commas and blank spaces are not permitted within the constant.
 2.The constant can be preceded by minus (-) sign if required.
 3.The value of a constant must be within its minimum bounds of its specified data type.

There are two ways of creating symbolic constants in c++.


1. using the qualifier const.
2. defining a set of integer constants using enum keywords.
In both C and C++, any value declared as const can‘t be modified by the program in any way.
In C++, we can use const in a constant expression. Such as
const int size = 10 ;
char name (size) ;
This would be illegal in C. const allows us to create typed constants instead of having to use
#defme to
create constants that have no type information.
const size=10;
Means
const int size =10;
C++ requires a const to be initialized. ANSI C does not require an initializer, if none is given, it
initializes the const to 0.
In C++ const values are local and in ANSI C const values are global .However they can be made
local

Object oriented programming [BCS & BIT] Page 21


made local by declaring them as static .In C++ 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
};

Manipulators:
Manipulators are the operators used to format the data that is to be displayed on screen.The most
commonly
used manipulators are endl and setw
endl:-it is used in output statement and inserts a line feed. It is similar to new line character
(―\n‖)
ex:
………………..
cout<<‖a=2‖<<endl;
cout<‖name=sunil‖<<endl;

setw:-
this manipulator allows a specified width for a field that is to be printed on screen
and by default the value printed is right justified.This function is available in header file
iomanip.h

example
#include<iostream.h>
#include<iomanip.h>
using namespace std;
int main()
{
int s=123;

Object oriented programming [BCS & BIT] Page 22


cout<<"s="<<setw(10)<<s ;
}
output
s=
123

Control statements:-
The flow of execution of statements in a program is called as control. Control
statement is a statement which controls flow of execution of the program. Control statements are
classified into following categories.
1. Sequential control statements
2. Conditional control statements
3. Unconditional control statements

Sequential control statements

Sequential control statements ensures that the instructions(or statements) are executed in the
samorder in which they appear in the program. i.e. By default system executes the statements in
the program in sequential order.

Conditional control statements

Statements that are executed when a condition is true. These statements are divided into three
categories. they are

 Decision making statements


 Switch case control statement
 Loop control statements or repetations

1.Decision making statements:- These statements are used to control the flow of
execution of a program by making a decision depending on a condition, hence they are
named as decision making statements.
Decision making statements are of four types
a. Simple if
b. if else
c. nested if else
d. If else ladder

Object oriented programming [BCS & BIT] Page 23


a)Simple if statement: if the test expression is true then if statement executes statements
that
immediately follow if
Syntax:
If(test expression)
{
List of statements;
}

/*largest of two numbers*/


#include<iostream.h>
int main()
{
int a,b;
cout<<―Enter any two integers:‖;
cin>>a>>b;
if(a>b)
cout<<―A is larger than B\n A=‖<<a;
if(b>a)
cout<<―B is larger than A\n A=‖<<b;
return 0;
}

Object oriented programming [BCS & BIT] Page 24


b) if –else statement:
If test expression is true block of statements following if are executed and if test
expression is
false then statements in else block are executed
if (test expression)
{
statement block1;
}
else
{
statement block2;
}

c)Nesting of if-else statements


It's also possible to nest one if statement inside another. When a series of decisions are
to be made.
If –else statement placed inside another if else statement
Syntax:
If(test expression)
{
If(test expression)
{
//statements
}
else
{

Object oriented programming [BCS & BIT] Page 25


//statements
}
}
else
{
}
}

example
/*largest of three numbers*/
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int a,b,c;
cout<<"Enter a,b,c values:";
cin>>a>>b>>c;
if(a>b)
{
if(a>c)
{
cout<<"A ia largest among three numbers\n";
cout<<"A= "<<a;
}
else
{
cout<<"C ia largest among three numbers\n";
cout<<"c= "<<c;
}

Object oriented programming [BCS & BIT] Page 26


}
else
{if(b>c)
{
cout<<"B ia largest among three numbers\n";
cout<<"B="<<b;
}
else
{
cout<<"C ia largest among three numbers\n";
cout<<"c="<<c;
}
}
getch();
return 0;
}

d) if else ladder
The nesting of if-else depends upon the conditions with which we have to deal.
The condition is evaluated from top to bottom.if a condition is true the statement
associated with it is executed.
When all the conditions become false then final else part containing default statements
will be executed.
Syntax
if(condition1)
statement1;
else if(condition2)
statement 2;
else if(condition3)
statement n;
else
default statement.
statement-x;

Object oriented programming [BCS & BIT] Page 27


Example
#include<iostream>
using namespace std;
int main()
{
int per;
cout<<"Enter percentage";
cin>>per;
if(per>=80)
cout<<"Secured Distinction"<<endl;
else if(per>=60)
cout<<"Secured First Division"<<endl;
else
if(per>=50)
cout<<"Secured Second Division"<<endl;
else if(per>=40)
cout<<"Secured Third Division"<<endl;
else
cout<<"Fail"<<endl;
}

THE SWITCH STATEMENT or MULTIWAY SELECTION :


In addition to two-way selection, most programming languages provide another selection
concept known as multiway selection. Multiway selection chooses among several
alternatives.

If for suppose we have more than one valid choices to choose from then we can use
switch statement in place of if statements.
syntax
switch(expression)

Object oriented programming [BCS & BIT] Page 28


{.
case value-1:
block-1
break;
case value-2:
block-2
break;
--------
--------
default:
default block;
}

Loop control statements or repetitions:


A block or group of statements executed repeatedly until some condition is satisfied is
called Loop.
The group of statements enclosed within curly brace is called block or compound
statement.
We have two types of looping structures.
One in which condition is tested before entering the statement block called entry control.
The other in which condition is checked at exit called exit controlled loop.
Loop statements can be divided into three categories as given below
a. while loop statement
b. do while loop statement
c. for loop statement
a)WHILE STATEMENT :
It is an entry controlled loop. The condition is evaluated and if it is true then body of loop
is executed. After execution of body the condition is once again evaluated and if is true
body is executed once again. This goes on until test condition becomes false.

Object oriented programming [BCS & BIT] Page 29


While(test condition)
{
body of the loop
}
example
/*c program to find sum of n natural numbers */
#include<iostream>
using namespace std;
int main()
{
int i = 1,sum = 0,n;
cout<<"Enter N"<<endl;
cin>>n;
while(i<=n)
{
sum = sum + i;
i = i + 1;
}
cout<<"Sum of first natural numbers is:"<<sum<<endl;
return 0;
}

b) DO WHILE STATEMENT :
The while loop does not allow body to be
executed if test condition is false. The do while is an
exit controlled loop and its body is executed at least
once.

do
{
body
}while(test condition);

example
/*c program to find sum of n natural numbers */
#include<stdio.h>
int main()
{
int i = 1,sum = 0,n;

Object oriented programming [BCS & BIT] Page 30


cout<<‖Enter N"<<endl;
cin>>n
do{
sum = sum + i;
i = i + 1;
}
while(i<=n);
cout<<‖Sum of first‖<< n<<‖ natural numbersis:‖<<sum; return 0;
}
Note: if test condition is false. before the loop is being executed then While loop executes
zero number of times where as do--while executes one time

c)FOR LOOP :
It is also an entry control loop that provides a more concise structure
Syntax:
for(initialization; test expression; increment/decrement)
{
statements;
}

For statement is divided into three expressions each is separated by semi colon;
1.initilization expression is used to initialize variables
2.test expression is responsible of continuing the loop. If it is true, then the program
control flow goes inside the loop and executes the block of statements associated
with it .If test expression is false loop terminates
3.increment/decrement expression consists of increment
or decrement operator This process continues until test
condition satisfies.

Example
/*c ++ program to find sum of n natural numbers */
#include<iostream>
using namespace std;
int main()
{
int i ,sum = 0,n;
cout<<"Enter N";
cin>>n;
for(i=1;i<=n;i++)
{

Object oriented programming [BCS & BIT] Page 31


sum = sum + i;
}
cout<<"Sum of first"<<n<<" natural numbers is:"<<sum;
return 0;
}

Nested loops:
Writing one loop control statement within another loop control statement is called nested
loop
Statement

Ex:
for(i=1;i<=10;i++)
for(j=1;j<=10;j++)
cout<<i<<j;

example

/*program to print prime numbers upto a given number*/


#include<iostream>
using namespace std;
main()
{
int n,i,fact,j;
cout<<"enter the number:";
cin>>n;
for(i=1;i<=n;i++)
{
fact=0;
//this loop will check a no to be prime no. or not
for(j=1;j<=i;j++)
{

Object oriented programming [BCS & BIT] Page 32


if(i%j==0)
fact++;
}
if(fact==2)
cout<<i<<"\t";
}
}
Output:
Enter the number : 5
235

 Unconditional control statements:


Statements that transfers control from on part of the program to another part
unconditionally Different unconditional statements are
1)goto
2)break
3)continue

1.goto :- goto statement is used for unconditional branching or transfer of the program
execution to the labeled statement.

example
/*c program to find sum of n natural numbers using goto statement*/
#include<iostream>
using namespace std;
int main()
{
int i ,sum = 0,n;
cout<<"Enter N";
cin>>n;
i=1;
L1:
sum = sum + i;

Object oriented programming [BCS & BIT] Page 33


i++;
if(i<=n) goto L1;
cout<<"Sum of first "<<n<<" natural numbers is"<<sum;
return 0;
}

break:-
when a break statement is encountered within a loop ,loop is immediately exited and the
program continues with the statements immediately following loop.

Example
/*c++ program to find sum of n natural numbers example use of break statement*/
#include<iostream>
using namespace std;
int main()
{
int i ,sum = 0,n;
cout<<"Enter N";
cin>>n;
i=1;
L1:
sum = sum + i;
i++;
if(i>n) break;
goto L1;
cout<<"Sum of first‖<<n<<‖natural numbers is:"<<sum;
return 0;
}

Continue:
It is used to continue the iteration of the loop statement by skipping the statements
after continue statement. It causes the control to go directly to the test condition and then
to continue the loop.

Object oriented programming [BCS & BIT] Page 34


Example

/*c program to find sum of n positive numbers read from keyboard*/


#include<iostream>
using namespace std;
int main()
{
int i ,sum = 0,n,number;
cout<<"Enter N";
cin>>n;
for(i=1;i<=n;i++)
{
cout<<"Enter a number:";
cin>>number;
if(number<0) continue;
sum = sum + number;
}
cout<<"Sum of"<<n<<"numbers is:"<<sum;
return 0;
}

Object oriented programming [BCS & BIT] Page 35


Classes and Objects
Classes in C++ :
In OOP data must be represented in the form of a class .
Class is a group of objects that share common properties and relationships

 A class contains variables(data members) for storing data and functions(member


functions) to specify various operations that can be performed and hence it is only
logical representation of data and not physical representation.
 A class is a user defined data type, which consists of both data members and
member functions into a single unit.
 class is a blue print of an object.
 Once a class has been defined we can create any number of objects.
 Each object is associated with the data of type class which they were created.
 class provides the concept of Encapsulation.
 class provides the concept of Data hiding with private declarations.
 A class is declared by the keyword class.

Generally a class specification has two parts:-


a) Class declaration
b) Class function definition

The class declaration describes the type and scope of its members. The class
function
definition describes how the class functions are implemented.

a) Class declaration

Syntax:-

Object oriented programming [BCS & BIT] Page 36


Access Control:
Access specifier or access modifiers are the labels that specify type of access
given to members of a class. These are used for data hiding. These are also called
as visibility modes.
There are three types of access specifiers
1.private
2.public
3.protected

1.Private:
If the data members are declared as private access then they cannot be accessed
from other functions outside the class. It can only be accessed by the functions
declared within the class. It is declared by the key word „private‟ .
2.public:
If the data members are declared public access then they can be accessed from
other functions outside the class. It is declared by the key word „public‟ .
3.protected:
The access level of protected declaration lies between public and private. This
access
specifier is used at the time of inheritance
Note:- If no access specifier is specified then it is treated by default as private

Example:

#include<iostream>
using namespace std;
class student
{
//private:
int sid;
char sname[20];
public:
void getdata()
{
cout<<"Enter STUDENT ID : ";
cin>>rollno;
cout<<"Enter STUDENT NAME : ";
cin>>sname;
}
void putdata()

Object oriented programming [BCS & BIT] Page 37


{
cout<<"\n Student ID : "<<sid;
cout<<"\n student Name : "<<sname;
}
};
int main()
{
student s;
s.getdata();
s.putdata();
return 0;
}

OBJECTS
An object is said to be an instance of a class. Defining an object is similar to
defining a variable of any data type: Space is set
aside for it in memory. Defining objects in this way means creating them. This is
also called instantiating them. Once a Class has been declared, we can create
objects of that Class by using the class Name like any other built-in type variable.

syntax :
class_name object_name;
Ex:
student s;

We have two methods to create objects to a class

Method 1:
We will create the objects in main() as follows:
Syntax:
classname objectname;

Example:
Employee e1;

In the above example e1 is an object of a class Employee.

We can create multiple objects at a time to a class;

Object oriented programming [BCS & BIT] Page 38


Syntax:
classname objectname1, objectname2,………. Objectname n;
Example:
Employee e1,e2,e3;

Method2:
We can create the objects at time of class declaration itself
That is, Objects can also be created when a class is declared by placing their
names
immediately after the closing brace as follows.

Syntax:
class classname
{
Datamembers;
Member functions;
} objectnam1,objectname2,……objectname n;

Example:
Class Employee
{
int eid;
float salary;
} e1,e2,e3;

time
declaration of class.

class item
{
-----------
-----------
-----------
}x ,y ,z;
would create the objects x ,y ,z of type item.

Object oriented programming [BCS & BIT] Page 39


Accessing class members

An object can be declared in the main(), and member functions are declared in
class in
public section so always a member function can be called by using object.
The object can access the public data member and member functions of a class by
using dot(.) and arrow(->) operators.

syntax:
[object name] [operator] [Member name]

Example
class xyz
{
Int x;
Int y;
public:
int z;
};
---------
----------
xyz p;
p. x =0; //error . x is private
p, z=10; //ok ,z is public

C++ program to find sum of two numbers using classes


#include<iostream.h>
#include<conio.h>
class A{
int a,b,c;
public:
void sum(){
cout<<"enter two numbers";
cin>>a>>b;
c=a+b;
cout<<"sum="<<c;
}
};
int main(){
A u;

Object oriented programming [BCS & BIT] Page 40


u.sum();
getch();
return(0);
}

DEFINING MEMBER FUNCTION:


Member functions can be defined in two places
• Outside the class definition
• Inside the class function

INSIDE THE CLASS DEFINATION:


Another method of defining a member function is to replace the function declaration by the
actual function definition inside the class .

Example:
class item
{
Int number;
float cost;
public:
void getdata (int a ,float b);
void putdata(void)
{
cout<<number<<endl; cout<<cost<<endl;
}
};

Object oriented programming [BCS & BIT] Page 41


OUTSIDE THE CLASS DEFlNAT1ON;
A public member function can also be defined outside of the class with a special type of operator
known as Scope Resolution Operator represents by :: (double colon)

This is used to access global variables if same variables are declared as local and global

#include<iostream.h>
int a=5;
void main()
{
int a=1;
cout<<‖Local a=‖<<a<<endl;
cout<<‖Global a=‖<<::a<<endl;
}

Scope resolution operator(::) is used to define a function outside a class


The scope resolution operator is used to reference the global variable or member function that is
out of scope. Therefore, we use the scope resolution operator to access the hidden variable or
function of a program.
syntax

return_type class_name::function_name(parameters)

function_body;

Example

#include <iostream>

using namespace std;

class Example

private:

int val;

public:

Object oriented programming [BCS & BIT] Page 42


//function declarations

void init_val(int v);

void print_val();

};

//function definitions

void Example::init_val(int v)

{ val=v;

void Example::print_val()

cout<<"val: "<<val<<endl;

int main()

//create object

Example Ex;

Ex.init_val(100);

Ex.print_val();

return 0;

Example 2

#include<iostream>

using namespace std;

class item

Object oriented programming [BCS & BIT] Page 43


{

int number;

float cost;

public:

void getdata( int a, float b);

void displaydata( void)

cout<<"number:"<<number<<endl;

cout<<"cost :"<<cost<<endl;

};

void item ::getdata(int a, float b)

number=a;

cost=b;

int main()

item x;

cout<<"\n object x"<<endl;

x.getdata( 100,299.95);

Object oriented programming [BCS & BIT] Page 44


x.displaydata();

item y;

cout<<"\n object y"<<endl;

y.getdata(200,175.5);

y.displaydata();

NESTING OF MEMBER FUNCTION:

A member function can be called by using its name inside another member function of the same
class. This is known as nesting of member functions.
Example

#include<iostream>

using namespace std;

class set

int m,n;

public:

int input(void);

void display(void);

int largest(void);

};

int set::largest(void)

if(m>n)

Object oriented programming [BCS & BIT] Page 45


{

return m;

else

return n;

int set::input(void)

cout<<"input values of m and n:";

cin>>m>>n;

return 0;

void set::display(void)

cout<<"largest value="<<largest()<<"\n";

int main()

set A;

A.input();

A.display();

Object oriented programming [BCS & BIT] Page 46


output:

Input values of m and n: 30 17

largest value= 30

STATIC CLASS MEMBERS


 Static Data Members
 Static Member Functions

Static Data Members:


A data member of a class can be qualified as static. A static member variable has certain special
characteristics:

 It is initialized to zero when the first object of its class is created. No other initialization is
permitted. It is initialized before any object of this class is created, even before the main
starts.

 Only one copy of that member is created for the entire class and is shared by all the
objects of that class, no matter how many objects are created.
 It is visible only within the class, but its lifetime is the entire program.
 Static data member is defined by keyword „static‟

Syntax:
Data type class name::static_variable Name;
Ex: int item::count;

Example
#include<iostream>
using namespace std;
class item
{
static int count;
int number;
public:
void getdata(int a)
{
number=a;
count++;

Object oriented programming [BCS & BIT] Page 47


}
void getcount()
{
cout<<"\ncount is"<<count;
}
};
int item::count;//decleration
int main()
{
item a,b,c;
a.getcount();
b.getcount();
c.getcount();
a.getdata(10000);
b.getdata(20000);
c.getdata(30000);
cout<<"\nAfter reading data";
a.getcount();
b.getcount();
c.getcount();
return 0;
}

Static Member Functions


Like static member variables, we can also have static member functions. A member function that
is declared static has the following properties:

 A static function can have access to only other static members (functions or variables)
declared in the same class.
 A static member function is to be called using the class name (instead of its objects) as
follows: class-name :: function-name;

example
#include<iostream.h>
class test
{
int code;
static int count;
public:

Object oriented programming [BCS & BIT] Page 48


void setcode()
{
code=++count;
}
void showcode()
{
cout<<‖object number‖<<code;
}
static void showcount()
{
cout<<‖count‖<<count;
}
};
int test::count;
int main()
{
test t1,t2;
t1.setcode();
t2.setcode();
test::showcount();
test t3;
t3.setcode();
test::showcount();
t1.showcode();
t2.showcode();
t3.showcode();
return 0;
}
Output:
count 2
count 3
object number 1
object number 2
object number 3
example 2
// Static member in a class
#include <iostream>

using namespace std;

class Student {

Object oriented programming [BCS & BIT] Page 49


public:

// static member

static int total;

// Constructor called

Student()

total += 1;

};

int Student::total = 0;

int main()

// Student 1 declared

Student s1;

cout << "Number of students:" << s1.total << endl;

// Student 2 declared

Student s2;

cout << "Number of students:" << s2.total << endl;

// Student 3 declared

Student s3;

cout << "Number of students:" << s3.total << endl;

return 0;

output

Number of students:1

Object oriented programming [BCS & BIT] Page 50


Number of students:2

Number of students:

FRIEND FUNCTIONS:
The private members cannot be accessed from outside the class. i.e.… a non
member function cannot have an access to the private data of a class. In C++ a non
member function can access private members by making the function friendly to a class.

Definition:
A friend function is a function which is declared within a class and is defined outside the
class.
It does not require any scope resolution operator for defining . It can access private
members of a class. It is declared by using keyword “friend”
A function or an entire class may be declared to be a friend of another class.
A friend of a class has the right to access all members (private, protected or public) of the class

Syntax for a friend function


class ABC
{
---------
---------
public:
--------
----------
friend void xyz(void);
};

class A
{
friend class B; // Class B is a friend of class A private:
// private members of A
int i;
float f;
public: // public members of A
void getdata(int a);
};
class B{ // Class B
int j;

Object oriented programming [BCS & BIT] Page 51


public: void showdata(void)
{
cout << s.i;
} // B can access private members of A
};

A friend function has the right to access all members (private, protected or public) of the class.

A friend function possesses certain special characteristics:


 It is not in the scope of the class to which it has been declared as friend.
 Since it is not in the scope of the class, it cannot be called using the object of that class. It
can be invoked like a normal function without the help of any object.
 Unlike member functions, it cannot access the member names directly and has to use an
object name and dot membership operator with each member name.
 It can be declared either in the public or private part of a class without affecting its
meaning.
 Usually, it has the objects as arguments.

example
#include<iostream>
using namespace std;

class base {
int val1, val2;
public:

void get() {
cout << "Enter two values:";
cin >> val1>>val2;
}
friend float mean(base ob);
};

float mean(base ob) {


return float(ob.val1 + ob.val2) / 2;
}

int main() {
base obj;

Object oriented programming [BCS & BIT] Page 52


obj.get();
cout << "\n Mean value is : " << mean(obj);
}

A function friendly to two classes


#include<iostream>
using namespace std;
class abc;
class xyz
{
int x;
public:
void setvalue(int x)
{ x-=1;
}
friend void max (xyz,abc);
};
class abc
{
int a;
public:
void setvalue( int i)
{a=i;
}
friend void max(xyz,abc);
};
void max( xyz m, abc n)
{
if(m . x >= n.a)
cout<<m.x;
else
cout<< n.a;
}
int main( )
{
abc j;
j . setvalue( 10);
xyz s;
s.setvalue(20);
max( s , j );

Object oriented programming [BCS & BIT] Page 53


return(0);
}

INLINE FUNCTIONS:
Definition:
An inline function is a function that is expanded in line when it is invoked.
Inline expansion makes a program run faster because the overhead of a function call and
return is eliminated. It is defined by using key word ―inline‖

Necessity of Inline Function:


 One of the objectives of using functions in a program is to save some memory space,
which becomes appreciable when a function is likely to be called many times.
 Every time a function is called, it takes a lot of extra time in executing a series of
instructions for tasks such as jumping to the function, saving registers, pushing arguments
into the stack, and returning to the calling function.
 When a function is small, a substantial percentage of execution time may be spent in such
overheads.
 One solution to this problem is to use macro definitions, known as macros. Preprocessor
macros are popular in C. The major drawback with macros is that they are not really
functions and therefore, the usual error checking does not occur during compilation.
 C++ has different solution to this problem. To eliminate the cost of calls to small
functions, C++proposes a new feature called inline function.

General Form:
inline function-header
{
function body;
}

example
#include<iostream>
using namespace std;
inline float mul(float x, float y)
{
return (x*y);
}
inline double div(double p, double q)
{
return (p/q);
}

Object oriented programming [BCS & BIT] Page 54


int main()
{
float a=12.345;
float b=9.82;
cout<<"mulitply"<<mul(a,b)<<endl;
cout<<"divide"<<div(a,b);
return 0;
}

Properties of inline function:


1.Inline function sends request but not a command to compiler
2.Compiler may serve or ignore the request
3.if function has too many lines of code or if it has complicated logic then it is executed
as normal function

Situations where inline does not work:


 A function that is returning value , if it contains switch ,loop or both then it is treated as
 normal function.
 If a function is not returning any value and it contains a return statement then it is treated
as normal function
 If function contains static variables then it is executed as normal function
 If the inline function is declared as recursive function then it is executed as normal
function.

Overloading Member Function


 Overloading is nothing but two or more functions is defined with same name but different
Parameters.
 Function overloading can be considered as an example of polymorphism feature in C++.
 Function overloading is a compile-time polymorphism.

Rules for Function overloading :


An overloaded function must have :
Different type of parameters
ex: void test(int a);
void test(float a);
Different number of parameters
ex: void test();
void test(int a);
Different sequence of parameters
ex: void test(int a , float b);

Object oriented programming [BCS & BIT] Page 55


void test(float a , int b);

To demonstrate function over loading


#include<iostream>
using namespace std;
class addition {
public:
int add(int a, int b);
int add(int a, int b,int c);
double add(int a, double b);
double add(double a , int b);
};
int addition::add(int a, int b) {
cout<<"Function 1"<<endl;
return (a+b);
}
int addition::add(int a, int b, int c) {
cout<<"Function 2"<<endl;
return (a+b+c);
}
double addition::add(int a, double b) {
cout<<"Function 3"<<endl;
return (a+b);
}
double addition::add(double a,int b) {
cout<<"Function 4"<<endl;
return (a+b);
}
int main() {
addition obj;
cout<<"Addition of two integers : "<<obj.add(1,2)<<endl;
cout<< "Addition of three integers : "<<obj.add(3,4,5)<<endl;
cout<<"Addition of integer and double : "<<obj.add(4,5.6)<<endl;
cout<<"Addition of double and integer : "<<obj.add(7.4,5)<<endl;
return 0;
}

Object oriented programming [BCS & BIT] Page 56

You might also like