Вы находитесь на странице: 1из 79

PAN African e-Network Project

PGDIT
Object Oriented Programming
Semester 2nd
Session - 1

Dr. Bhawna Minocha

Welcome
to
Object Oriented
Programming

Session Outline

Genesis of C++
Structured vs. Object Oriented Programming
Basics Concepts of Object Oriented Programming
Structure of C++ program
C++ Comments
A simple C++ program with explanation
Using streams for input and output (cin , cout)
Placement of variable declarations
The const qualifier
Executing a C++ program
A Class in C++
Synonyms
Practice Questions & answers

GENESIS OF C++
Factors that contributed to the evolution
Increasing complexity of the problem domain.
Difficulty in capturing the complexity of the problem domain
through procedural languages(like C, Fortran, Pascal)
Difficulty in modeling real-world objects through procedural
languages.

GENESIS OF C++
Growing demands on software in terms of
Correctness
Maintainability
Reusability
Scalability
Openness and interoperability
Integrity

GENESIS OF C++
Commercial viability
A huge investment in C lead to the incorporation of object
oriented features with C leading to
C++ is a superset to C and C++ = C +OOPs.
C++ provides object-oriented programming (OOP).
OOPs was invented to overcome the drawbacks of the
pop(Procedure-Oriented Programming).

Structured
Vs
Object-oriented
Development

Structured Programming
In the structured approach, the problem is
viewed as a sequence of things to be done,
such as reading, calculating and printing.
A number of functions are written to
accomplish these tasks.
The primary focus is on functions.
A typical program structure for procedural
programming is shown in the next slide.

Typical structure of structureoriented programs


Main Program

Function - 1

Function - 2

Function - 4

Function - 3

Function - 5

Function - 6

Structured programming basically consists of


writing a list of instructions for the computer
to follow, and organizing these instructions
into group known as functions.
While we concentrate on the development of
functions, very little attention is given to the
data that are being used by various functions.
In a multi-function program, many important
data items are placed as global so that they
may be accessed by all the functions.
Each function may have its own local data.

Relationship of data and functions in


Structured programming
Global Data

Global Data

Function - 1

Function - 1

Function - 1

Local Data

Local Data

Local Data

Global data is more vulnerable to an inadvertent


change by a function.
In a large program it is very difficult to identify what
data is used by which function.
In case we need to modify an external data structure,
we should also revise all functions that access the
data.
Another serious drawback with the Structured
approach is that it does not model real world
problems very well.
This is because functions are action-oriented and do
not really correspond to the elements of the problem.

Object-Oriented programming paradigm


Object-oriented programming (OOP) is
organized around "objects" rather than
"actions, data rather than logic.
OOP treats data as a critical element in the
program development and does not allow it to
flow freely around the system.
OOP allows us to decompose a problem into a
number of entities called objects and then
builds data and functions around these entities.

Organization of data and functions in


OOP
Data

Data
Functions

Functions
Object A

Object B
Functions

Data

Object C

Comparison of the Two


Approaches
Software projects are complex, and decomposition
(divide-and-conquer) is the primary strategy to deal
with its complexity by breaking a problem up into
manageable units.
Prior to object-oriented analysis and design, the
most popular approach to decomposing a problem
was Structured Analysis and Design, whose
dimension of decomposition is primarily by function
or process, resulting in a hierarchical breakdown of
processes composed of sub-processes.

Object-oriented analysis and design


emphasizes decomposing a problem space
by objects rather than by functions.
The following figure illustrates the primary
distinction between the two approaches
presented.

Library
Management
System

Comparison
b/w OOAD &
SSAD

Object-Oriented A/D

Structured A/D

Decompose by
objects or concepts

Decompose by
functions or processes

Book

Catalog

System

Library
Librarian

Record
Issues

Add To
Stock

Report
Fines

Distinction between POP and OOP


Programming
POP

OOP

Procedure oriented programming.

Object oriented programming.

Emphasis is on procedure.

Emphasis is on data rather than


procedure

Follows top-down approach.

Follows bottom-up approach.

Data is not secure.

Data is secure by encapsulation.

Large programs are divided in to


smaller programs known as
functions

Programs are divided in to what are


known as objects.

Basic Concepts of Object Oriented Programming

1.
2.
3.
4.
5.
6.
7.

Objects
Classes
Encapsulation
Abstraction
Inheritance
Polymorphism
DynamicBinding&
MessagePassing

1
2

7
5

Objects
Objects are often used to model real world entities
that we normally find in everyday life.
An object can be a person , place , thing ,concept or
anything we see in the real world . Some common
examples of an object include car ,book, computer ,
apple etc.
The principal building blocks of object-oriented
programming.
Each object is a programming unit consisting of data
(variables) and functionality (methods).

OBJECT:STUDENT

Data

A. Name
B. Date Of Birth
C. Marks
....................

A
2

B
Functions

1. Total
2. Average
3. Display
................

Objectscontaindata(likeName,DOB,Marks)andfunctions
(likeTotal,averageanddisplay)tomanipulatethatdata.

Objects
Each object possess the following characteristics.
Each object has an identity and are distinguishable.
Data and functions are binded together to form an
object.
Objects in the system communicate with each other
using the concept of message passing.
Objects store data which is manipulated by its
functions.
Since all software applications serve people living in the
real world, then that software should mirror the real world
as closely as possible, both in its workings and in its
appearance :: thats the reason to use objects

Class
A class is a general specification or description for a
set of objects that defines their common structure
(data), behaviour (methods), and relationships
(inheritance).
A class is a prototype that defines the variables and
methods common to all objects of a certain kind.
Once a class has been defined, we can create any
number of objects belonging to that class.
If fruit has been defined as a class, then the
statement fruit mango; will create an object mango
belonging to the class fruit.

Why use classes?


The object is a basic key concept of Object
Oriented Programming but still we focus on
classes because classes provide us the ability
to generalize similar type of objects.
Classes provide us a set of common
definitions for similar type of objects.
Operations can be written once for each class ,
so that all the objects in a class can take
benefit from the code reuse.

Distinction between Object and Class


Object

Class

Objects may be created and destroyed at run


time.

Once we have defined a class, it


exists all the time a program is
running

Data and functions that operate on that data


are binded together to form an object.

A collection of similar type of objects


is called a class

Object is an instance of a class.

Class is a set of object that share


common attributes and behaviours.

Table , chair , sofa are examples of objects.

Furniture is an example of class


which has table ,chair , sofa objects.

Encapsulation
Encapsulation

Encapsulation is the wrapping up of data and function


into single unit called object.
The only way to access the data of an object is through
the function which are wrapped in the class.
Consider two classes.Library class and a Student Class.
The Library class encapsulates data (like Book Id,book
author book title, no. of copies) and functions like
issue(),book_status() and book_description () in to a
single unit. As shown in next slide. In the similar manner
the Student class encapsulates data and functions as
shown in next slide. The two classes are independent of
each other.

Encapsulation
Book Id
Book author
Book title

Issue()
Book_status
Book_description

Library Class

Roll no
Name
Class

Input()
Show()

Student Class

ADVANTAGES OF ENCAPSULATION

With Encapsulation Data Hiding can be accomplished.


It protects the data of a class from accidental manipulation
or misuse by the functions which are outside the class.
Any changes made in the data and functions of a class does
not make any effect to other classes.
Classes are independent of each other.

Abstraction
Abstraction Simplicity is good; complexity is bad.
Abstraction is a process that involves identifying the essential
features without including the internal details.
A good abstraction is the one that emphasizes details that are significant
and suppresses details that are not.
Let us take a real world example ::
Consider an example of a Television which consists of features such as
changing the channel ,ON/OFF switch etc. User interacts with television
using interfaces like channel changer, volume controller, and power button
without going in to internal details of the working of each of the interface.
The user is not concerned about how it receives signals over the air.
,translate them and display on the screen. So,it shows how the internal
complexity of working of the television is hidden from the user.

Abstraction
Abstraction
In object oriented programming , classes uses the concept of Abstraction.
A class encapsulates the relevant data and functions that operate on data
by hiding the complex implementation details from the user . In other
words ,user needs to focus on what a class does rather than how it will be
implemented.
The following diagram shows that the basic concept of Abstraction.

Inheritance
Inheritance is the process by which objects of one class
acquire properties of objects of another class.
Types of class in inheritance.
1. Base class.
2. Derived class.

Grand Father

Father

// Base class

// Derived class

Inheritance
Inheritance is the process by which one
object acquires the properties of one or more
other object. It supports the concept of
hierarchical classification (top-down).
An object need to define only those qualities
that make it unique within its class.
It implements "is-a" relationships between
objects.
Inheritance creates a hierarchy of related
classes (types) which share code and
interface.

INHERITANCE EXAMPLES
Base Class

Derived Class

Employee

Manager
Researcher
Worker

Account

Checking Account
Saving Account

Generalization/Specialization
Generalization/Specialization represents the is
a relationship set, an essential element of the
object oriented paradigm. The main idea in
Generalization/ Specialization is that one
object class (the specialization) is a subset of
another (the generalization).
A generalization-specialization (gen-spec)
relationship states that one object is a kind-of
(or is-a) the other, and that the other is a
generalization of the object

Specialization
Specialization is either:
the process of defining a new object based on a
(typically) more narrow definition of an existing
object, or
an object that is directly related to, and more
narrowly defined than, another object.
A specialization relation requires that every
instance of the subtype be an instance of the
supertype.
It is common to say that everything that is true for a
generalization is also true for its corresponding
specialization.

POLYMORPHISM
The word Polymorphism is derived from two Greek
words Poly means many and morphs means forms.
So , polymorphism means the ability to take many
forms.
Polymorphism means one name, multiple forms. It
allows us to have more than one function with the
same name in a program .
It also allows overloading of operators so that an
operation can exhibit different behaviors in different
instances.

Basics of OOP
Polymorphism Example
Ex:-addition(+)
For two numbers ,the operation will generate a sum.
For two strings , then the operation would produce a
third string by concatenation.

Basics of OOP
Dynamic Binding

Binding refers to the linking of a function call to the


code of the function to be executed in response to
the function call. Binding is of two types::
Static Binding or Early Binding
Dynamic Binding or Late Binding
Static Binding:: In static Binding, the linking of
function call to the code of the function to be
executed in response to the function call is made at
compile time.
Static Binding:: In static Binding, the linking of
function call to the code of the function to be
executed in response to the function call is made at
run time.

MESSAGE PASSING
In Object oriented programming (OOP) different objects
communicate with each other using the concept of Message
Passing. From the programmer point of view ,message passing
provides an easy way of modeling real world problems on the
computer. Objects communicate with each other in the same way as
human beings exchange messages among themselves.
A message comprises of the name of the object , name of the
function and any information (arguments) to be sent to the object.
For example :If a user wants to check the balance of his account ,
he simply sends the message getbalance to the object account by
passing the information account_no. as shown below
account. getbalance (account_no)
account:: Object
Getbalance:: Message
account_no :: Argument or Onformation

Structure Of C++ Program


Documentation Section :: which includes the comments to tell the programs
purpose. It improves the readability of the program.
Preprocessor Directive :: includes preprocessor directives like # include, #
define which is a message to the preprocessor
Global Declaration Section:: includes global variables which are visible
throughout the program. In general, use of global variables should be avoided.
Class Section :: describes information about classes present in the program.

Main Program Section:: from here the execution of program actually starts.
Eg:: int main()
{ // Executable Part
}
SubProgram Section :: includes user defined functions.

C++ Comments
C++ supports the C comment format where /* begins a
comment and */ ends it.
The // also starts a comment in C++ (unless it is inside a
string). Everything to the end of the current line is a
comment.
e.g.,
/* This is a comment */
//

This is also a C++ comment

//

This is invalid
in the next line

/*

This is valid in
the next line */

C++ Comments
Good practice: C++ style of comment is recommended as can
be seen in the following example.
C++ style
if(a>b)
{ //int temp=a;
//swap a, b
//a=b;
//b=temp;
}
C style
if(a>b)
{ /*
int temp=a; /*swap a,b*/
a=b;
b=temp; */
}

A Simple program in C++ to add two numbers


// To add two numbers
#include <iostream.h> // preprocessor directive
#include <conio.h>
int main() // main() function heading
{
int a , b , sum; // variable declaration
cout << Enter number a = ; // Output statement
cin >> a; // Input statement
cout << Enter number b = ;
cin >> b;
sum=a+b;
cout << Sum is <<sum; // Output statement
getch();
return 0;

Explanation of the previous program


The first line :: specifies the comment describing the purpose of the program. It
is non executable statement.
The second line :: contains a preprocessor directive that instructs the compiler to
include the file iostream.h(Input /Output header file) at this point. This file must be
included in the program to perform any Input /Output operations.
Similarly the header file conio.h is handled.
The fourth line :: main () is a entry point of a programs execution. Every C++
program must contain only one main function.
It is necessary to specify the return data type of every function used in C++. The
return type of main is always int. the last statement return 0; tells main to return
value 0 to the calling environment. Any other value specified with return statement
indicates that the program has not run properly.
The remaining lines :: comprises the set of statements which includes variables
declaration , input statements, and output statements.
cin statement is used to input any value from the keyboard and
cout statement is used to display any message or value on the screen.

On executing previous C++ program , we


get
Enter Number a=7 //(press enter)
Enter Number b=7 //(press enter)
Sum is 14

Streams

The Standard Output Stream


The name cout represents the standard output stream. It can be
used to send messages to the standard output (the screen).

The Standard Error Stream


The name cerr represents the standard error stream. It can be
used to send messages to the screen, especially from programs
that have their standard output redirected to another file or device.

The Standard Input Stream


The name cin represents the standard input stream. It can be used
to read data typed from the keyboard.
Any built-in data type may be used with cout, cerr and cin without a
format string, unlike printf.

Getting output onto the screen


include the <iostream.h> header file
use cout <<
use additional << to combine multiple
elements together eg
cout << you entered << x;

use endl to add newline


cout << you entered << x << endl;

47

Getting input from the keyboard


include the <iostream.h> header file
declare a variable of a suitable type
eg int num_in;

use cin
eg cin >> num_in;

48

Getting input from the keyboard


##include <iostream.h>
int main( )
{
int x;
cout << "please enter an integer" << endl;
cin >> x;
cout << "you entered " << x << endl;
return 0;
}

49

Placement of Variable Declaration

C requires that all variables be declared at the beginning of a


block.
C++ allows the declaration of a variable anywhere in the code, but
before it is referenced.
Allows the placement of a variable closer to the code that uses it,
which makes the program more readable.
e.g.,

main()
{
cout << Enter a number ;
int num;
// declaration of variable within block
cin >> num;
cout << Number = << num;
}

Basic Data Types


Type

Bytes

Range

Char

-128 to 127

Unsigned char

0 to 255

Signed char

-128 to 127

Int

-32768 to 32767

Unsigned int

0 to 65532

signed int

-31768 to 32767

Short int

-31768 to 32767

Unsigned short int

0 to 65535

Basic Data Types


signed short int

-32768 to 32767

Long int

-2147483648 to
2147483647

signed long int

-2147483648 to
2147483647

signed long int

0 to 4294967295

Float

3.4E-38 to 3.4E+38

Double

1.7E-308 to
1.7E+308

Long double

10

3.4E-4932 to
1.1E+4932

BOOL
It takes only two values: true or false
true=1;
false=0;
eg: #include<iostream.h>
#include<conio.h>
void main()
{
bool b=32;
bool i=false;
cout<<b<<i;
int j=b+b;
bool k=b+b;
cout<<j<<k;
getch();
}

output
10
2 true

NOTE: Some compilers(such as


TurboC++ 3.0)do not support bool data
type.However ,compilers like Devc++,Bortland C++ 5.5 etc support this data
type.

PROGRAM TO SHOW RANGE OF


INTEGER DATATYPE
#include<limit.h>
void main()
{
cout<<Min value of int=<<INT_MIN<<\n;
cout<<Max value of int=<<INT_MAX<<\n;
cout<<Min value of uint=<<UINT_MIN<<\n;
cout<<Max value of uint=<<UINT_MAX<<\n;
cout<<Min value of long=<<LONG_MIN<<\n;
cout<<Max value of long=<<LONG_MAX<<\n;
getch();
}

output

Minimum value of int = -32768


Maximum value of int = 32767
Maximum value of unsigned int =65535
Maximum value of long int =2147483647
Maximum value ogf long int =-2147483648

The const Qualifier


used to declare constants, as in ANSI C
specifies that the variable is read-only, except during its onetime initialization.
const variables can only be given values at initialization time.
can be used as a replacement for constants defined with the
#define directive.
C++ allows const declarations in header files, unlike C
E.g.:
const int a=123;
Good practice:
Prefer const to preprocessor macro since const variable value is
available to symbolic debugger unlike # defined values

DIFFERENCE BETWEEN #DEFINE AND


CONST
1. Const is better than #define.
2. If we place const inside the function i.e. effect will
be localized in that function whereas if it is placed
outside the function, its effect will be global.
3. But #define is always global. It cant be localized.

Executing any High level C++ involves


following steps
Developing the source code program
Selecting and saving the appropriate file name .This saved file is known as source
code file.
Compile the program. After compilation the program changes to a object file if
there are no errors.
Now link the object code and other library codes that are required for execution.
On linking correctly an executable code is formed.
Now run the program to obtain the desired results.
If answer is correct then stop otherwise check for some logical error.

Executing your C++ Program


Invoking Compiler:: there are many C++ compilers like Borland C++,Turbo C++
etc. Well take Turbo C++ as an example.
Change the directory to C:\cd TC (If TC directory)
And then C:\TC\ cd BIN
Result :: C:\TC\BIN
Making a New Program:: Select New from the file menu in the editor and type
the file name as First.CPP (Note the extension)
Typing your Program:: Type the program as specified in the discussed example
in the editor window.
Saving the Program:: After typing the C++ source code (program) save it to the
disk by selecting SAVE from FILE menu.
Running the program:: Once we type and edit our C++ program source code,
we must compile the program by using ALT + F9

Executing your C++ Program


Compiling the Program:: Whenever you compile a program, a compilation
window appear on the screen. If there are no errors during compilation ,it will
display Success :Press any key message. The entries for warning and errors will
be zero and an object file with extension (.OBJ) is created. This Object file
contains machine language instructions that can be executed by the computer.
Running the program:: To Run A C++ program after compilation we use the
RUN option of Run menu item or press CTRL + F9 keys from the keyboard. It will
result in creating a file with the same name as the source file but with >EXE
extension like FIRST.EXE
The getch function:: in the program helps to display the result on the screen
automatically.

A Class in C++
Class is a user define data type.
Class is a collection of objects of similar type.
Class Declarations.
class name
{
Data types;
Member functions
};

What is a class ?
A class is
An abstract datatype similar to a C structure.
A representation of objects and the sets of operations that can
be applied to such objects.

Class consists of Data members and methods.

Definition of a class

General form of a class :


Class class_name
{
Data Members;
Methods;
};

e.g.,
Class A
{
int i ;
char *strng;
Void f (int , char *);
int g() ;
};

Definition of a class (Contd)


e.g.,
Class Circle
{
int radius;
int XCentre;
int YCentre;
int GetRadius ();
int SetData;
int GetXCentre ();
int GetYCentre ();
};

Definition of a class (Contd)


private, protected,public are called visibility labels.

The members that are declared private can be accessed


only from within the class.

Public members can be accessed from outside the class


also.
In C++, data can be hidden by making it private.
Encapsulation is thus achieved.

Definition of a class (Contd)


Private area
No entry

Data
Functions
Public area

Entry
allowed

Data
Functions

Synonyms
Operations - "method selectors," "method
interfaces," "messages," or "methods",
services,member function, Instance Method
Object - instance, class instance, surrogate,
entity.
Class - type
Base Class - Super Class, Parent Class.
Derived Class - subtype, subclass, Child
class.

Member Variable - state variable, instance


variable, data member, attribute, field, slot.
Inheritance - subclassing, derivation, prefixing.
Abstract Class - interface, protocol, type,
virtual class, signature.
Object name - object reference, Handle, object
identifier.

Practice Questions 1
Q1 Identify the drawback of using
procedure-oriented programming, if any:
a) Data is hidden from external functions
b) New functions can be added whenever
necessary
c) Does not reflect real world problems
d) All of the above

Practice Questions 2
Q2 Which one of the following OOP
concepts enables reusability of
components?
a) Inheritance
b) Encapsulation
c) Polymorphism
d) All of the above

Practice Questions 3
Q3 The concept of hierarchical
classification is related to:
a) Abstraction
b) Inheritance
c) Function overloading
d) None

Practice Questions 4
Q4 Comments in C++ starts with
_______ symbol.
a) //
b) \\
c) **
d) None of the above

Practice Questions 5
Q5 return is an example of a
a) Keyword
b) Function
c) Statement
d) Comment

Practice Questions 6
Q6 The declaration of global variables
must be made
a)inside the function
b) outside the function
c) in a function header line
d) None of the above

Practice Questions 7
Q7 Consider the following code:
cout<< Welcome;
This is an example of
a) Return type
b) Function
c) Both a and c
d) C++ statement

Answers

Q1 c
Q2 a
Q3 b
Q4 a
Q5 a
Q6 b
Q7 d

Programming Practice Question


Q1 Create a simple C++ program to
display your name and fav. Color
Q2 Create a simple C++ program to
perform the four basic operations like
(+,-,*,/).
Q3 Write a program to read two
numbers from the keyboard and display
the larger value on the screen.

Thank You
Please forward your query
To :bminocha@amity.edu
Cc: manoj.amity@panafnet.com

Вам также может понравиться