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

Fundamentals of Object

Oriented Programming
Object Oriented Programming
� Software Evolution

� Characteristics Of Procedure Oriented Programming

� Characteristics Of Object Oriented Programming

� OOPS Concepts

� Benefits & Advantages Of OOPS

2
Software Evolution

1,0 Binary

Machine Language
Assembly Language

Procedure Oriented Programming

Object Oriented Programming

Layers of Computer Software


3
Characteristics of Procedure Oriented

Programming

� Emphasis is on doing things.

� Large Programs are divided into smaller

programs known as functions.

� Most of the functions share global data.

4
Characteristics of Procedure Oriented
Programming

� Data move openly around the system from

function to function.

� Functions transform data from one form to

another.

� Employs top – down approach in program

design.
5
Characteristics of Object Oriented
Programming

� Emphasis is on data rather than procedure.

� Programs are divided into what are known as


objects.

� Data structures are designed such that they


characterize the objects.

� Functions that operate on the data of an object are

tied together in the data structure.

6
Characteristics of Object Oriented
Programming

� Data is hidden & cannot be accessed by external

functions.

� Objects may communicate with each other

through functions.

� New data & functions can be easily added

whenever necessary.

7
� Follows bottom up approach in program
OOPs Concepts

� Object :-
1. Objects are the basic run time entities in an object
oriented system.
2. They may represent a person, a place, a table, a bank
account, a table of data or any item that the program
has to handle.
3. For ex:- If “Customer” & “Account” are two objects
in a program, then the customer object may send a
msg to the acct object requesting for the bank
balance.

Dalcomp Technologies 8
� Class :-
1. We just mentioned that objects contain data, & code to
manipulate that data, the entire set of data & code of an
object can be made a user defined data type with the help of
a Class.
2. For Ex.
Mango, Apple & Orange are the members of class fruit.
3. If the fruit has been defined as a class , then the
statement
fruit mango;
will create an object mango belonging to the class fruit.

9
�Data Abstraction :-

1. Abstraction is the process of extracting the relevant

properties of an object while ignoring nonessential

details.

2. The extracted properties define a view of the object.

3. Classes use the concept of abstraction & are defined as a

list of abstract attributes such as size, weight & cost &

functions to operate on these attributes.

10
Example Of Data Abstraction
4. For Ex. A car dealer might view a car from the standpoint
of its selling features. Relevant properties include price,
color, optional equipment, and length of warranty.

On the otherhand, a mechanic views the car from the


standpoint of the systems that require maintainance. Here
relevant properties include the type of oil, the size of the oil
filter, and the number and type of spark plug. The
properties of a car relevant to a car dealer are different from
the properties relevant to a mechanic. By focusing on the
relevant properties and ignoring irrelevant details, the
complexity of dealing with an object is reduced.
11
�Data Encapsulation:-
1. The binding of code and data into single
unit called class is known as Data
Encapsulation.

2. The data is not accessible to the outside


world & only those functions which are bind
inside the class can access it.

3. These functions works as the interface


between the objects data & code. 12
4. Writing data and code into the single unit

class is known as Data Hiding .

For Ex:- Medical Capsule i.e. One drug is

stored in bottom layer & another drug is

stored in upper layer these 2 layers are

combined in single capsule.

13
�Polymorphism:-
1. Polymorphism means “many forms and one interface”.
2. It allows us to have many function with the same name inside
a class.
Polymorphism

Compile Time Run-Time


(Static Binding) (Dynamic Binding)

Virtual
Operator Function Functions
Overloading Overloading
e.g. cin>>n; e.g. int add(int, int);
C = a>>2; Float add(float, int);

For Ex:- A man can be a Father, Son ,Husband,


Employee & Good Citizen. 14
�Inheritance:-

1. It is the process by which object of one class acquires the


property of object of another class, it support concept of
hierarchy classification.
2. In OOPS, inheritance provide the idea of reusability. i.e.
reusing the properties of superclass into its sub class .
3. We can add new properties or data to an new subclass.
4. For Ex. Father & son relationship.
Student

R no, Name Base Class Data Members


get(), put() Base Class Methods

Inheritance(Extending class)

Marks
Sub 1, Sub 2 Derived Class Data Members
get() , put() Derived Class Methods
15
� Dynamic Binding:-

1. Binding refers to the linking of a procedure call to the


code to be executed in response to the call.
2. Dynamic Binding (also known as late binding) means
that the code associated with a given procedure call is
not known until the time of the call at run time.
3. We see the Polymorphism example:-

Shape
Draw
()

Circle Object Triangle Object


Box Object
Draw(Circle) Draw(Box) Draw(Triangle)

4. For Ex. In the given figure, for draw() method ,at run
time, the code matching the object under current
16
reference will be called.
� Message Passing:-

1. An object oriented program consists of a set of objects


that communicate with each other.
2. Objects communicate with one another by sending &
receiving information much the same way as people
pass message to one another.

For Ex:-
Employee.Salary(name);

Object Information
Message

17
Benefits Or Advantages of OOPS
1.Through inheritance, we can eliminate redundant code &

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 & higher productivity.

3.The principle of data hiding helps the programmer to build

secure programs that cannot be invaded by code in other


18
parts of the program.
4. It is possible to have multiple instances of an object

to co-exist without any interference.

5. Object oriented systems can be easily upgraded from

small to large systems.

6. Message Passing techniques for communication

between objects makes the interface descriptions with

external systems much simpler.7. Software complexity

can be easily managed.

19
1.C++ is an Object Oriented Programming
Language.

1.It was developed by Bjarne Stroustrup at AT


& T Bell laboratories in New Jersey, USA in
1980’s as a successor of ‘C’.

1.To overcome drawbacks of ‘C’ Language


Stroustrup combine the features of Simula 67
& c into new languages called ‘C with Class’.

1.This Language is renamed to ‘C++’ in 1983.


20
Difference Between C & C++
1. C follows the procedural programming paradigm
while C++ is a multi paradigm language(procedural as
well as object oriented)

In case of C, importance is given to the steps or


procedure of the program while C++ focuses on the
data rather than the process.
Also, it is easier to implement/edit the code in case of
C++ for the same reason.

2. In case of C, the data is not secured while the data


is secured(hidden) in C++. 21
Difference Between C & C++
3. C is regarded as a low-level language(difficult
interpretation & less user friendly) while C++ has
features of both low-level(concentration on whats
going on in the machine hardware) & high-level
languages(concentration on the program itself) &
hence is regarded as a middle-level language.
4. C uses the top-down approach while C++ uses the
bottom-up approach
5. C is function-driven while C++ is object-driven

22
Difference Between C & C++
6. C++ supports function overloading while C
does not
7. We can use functions inside structures in C++
but not in C.
8. C++ allows the use of reference variables while C
does not
9. C contains 32 Keywords,C++ extends it to 52
Keywords
10. C++ is a superset of C while C is a superset of B.

23
First program of c++

� // my first program in C++


#include <iostream.h>
int main ()
{
cout << "Hello world!";
return 0;
}

24
Scope Resolution Operator
This Operator is used for:-
void test :: getdata()
1.To unhide the global
{
variable that might have
bought hidden by local x=10;y=20;
variables. }
2.To access members void main()
declared in class scope. {
test s;
For Ex:- class test s.getdata();
{ s.disp();
int x,y; getch();
public: }
void getdata();
void disp() Output:-
{
cout<<x<<“\t”<<y; 10 20
} 25
Example of Scope Resolution Operator to access global
variables:-
#include<iostream.h>

int m = 10; // global m

void main()
{
int m =20; // m local to main Output:-
{ We are in inner block
int k = m; k = 20
int m = 30; // m declared again m= 30
::m = 10
We are in outer block
cout<<“We are in inner block\n”;
m = 20
cout<<“k=“<<k<<“\n”; ::m = 10
cout<<“m=”<<m<<“\n”;
cout<<“::m=” << ::m << “\n”;
}
cout<<“n We are in outer block \n”;
cout<<“m=”<<m<<“\n”;
cout<<“::m=“ << ::m<<“\n”;
getch();
Dalcomp Technologies 26
}
Memory Management Operator
C++ Provides two operators for dynamic memory
allocation & deallocation:-

1) new operator :- This operator is used to


allocate memory for data element of any type.
Syntax : data type pointer = new datatype;
or
data type pointer = new type[size];
e.g. int *p;
p = new int; or p = new int[5];

27
2)delete operator :- When the memory allocated

dynamically is no longer in use must be free so that

it becomes available for future request of dynamic

memory this can be done using delete operator.

Syntax : delete pointer; or delete [] pointer

e.g. delete p; e.g. delete [] p;

28
Difference between memory management in c & c++
Memory management in C Memory management in C++
1. Dynamic memory 1. Dynamic memory
management is done using management is done using
function like
operators new & delete.
malloc(),calloc,realloc & free.
2. Operators execute faster.
2. Fuctions require additional
3. No need of any header file.
time.
4. The allocated memory can
3. We have to include header
be initialize to any value.
file to use this function.
5. The operators can be
4. The allocated memory can
only be initialize to 0. overloaded in c++.

5. This functions can not be


overloaded in c. 29
Reference Variables

� A reference variable is a new name given to an

existing variable.

� It is alice of the original variable.

� The reference variable cannot exist

independently i.e. It can only refer to an

existing variable.

30
Reference
Variables
�No memory is allocated to the reference

variable.

�The original name & reference name both

refers to the same memory location.

�The value can be access or change using

either the original name or reference name.

31
Example of reference variable

#include<iostream.h>
void main()
{
int x= 10;
clrscr();
cout<<“Value of x:”<<x;
int &rx = x; // reference variable
cout<<“Value of x:”<<rx;
Value of x:
rx = rx + 5;
10
cout<<“Value of x:”<<x; of x: 15
getch();
} Value of x: 10
Value

32
Functions in C++
• There are two types of functions in C programming:
1. Library Functions: are the functions which are
declared in the C++ header files such as ceil(x),
cos(x), exp(x), etc.

• 2. User-defined functions: are the functions which


are created by the C++ programmer, so that
he/she can use it many times. It reduces
complexity of a big program and optimizes the
code.
2 Ways of Function
• There are two ways to pass value or data to
function in C language:
• call by value:
• original value is not modified.
• In call by value, value being passed to the function
is locally stored by the function parameter in stack
memory location.
• If you change the value of function parameter, it is
changed for the current function only. It will not
change the value of variable inside the caller
method such as main().
PROGRAM
• #include <iostream>
• using namespace std;
• void change(int data);
• int main()
• {
• int data = 3;
• change(data);
• cout << "Value of the data is: " << data<< endl;
• return 0;
• } OUTPUT
• void change(int data) Value of the data is: 3
• {
• data = 5;
• }
Call by Reference
• call by reference.
• Original value is not modified in call by value but it
is modified in call by reference.
• In call by reference, original value is modified
because we pass reference (address).
• Here, address of the value is passed in the function,
so actual and formal arguments share the same
address space.
• Hence, value changed inside the function, is
reflected inside as well as outside the function.
• #include<iostream>
• using namespace std;
• void swap(int *x, int *y)
• {
• int swap;
• swap=*x;
• *x=*y;
• *y=swap;
• }
• int main()
• {
• int x=500, y=100;
• swap(&x, &y); // passing value to function
• cout<<"Value of x is: "<<x<<endl;
• cout<<"Value of y is: "<<y<<endl;
• return 0;
Pointer
• A pointer is a variable that contains the address of
another variable.

• It can be dereferenced with the help of


(*) operator to access the memory location to
which the pointer points.

• & (ampersand sign) Address operator: Determine


the address of a variable.

• ∗ (asterisk sign)Indirection operator Access the


value of an address.
• #include <iostream>
• using namespace std;
• int main()
• {
• int number=30;
• int ∗ p;
• p=&number;//stores the address of number variabl
e
• cout<<"Address of number variable is:"<<&number
<<endl;
• cout<<"Address of p variable is:"<<p<<endl;
• cout<<"Value of p variable is:"<<*p<<endl;
• return 0;
• }
this pointer
• Every object in C++ has access to its own address
through an important pointer called this pointer.
The this pointer is an implicit parameter to all
member functions. Therefore, inside a member
function, this may be used to refer to the invoking
object.
• Friend functions do not have a this pointer,
because friends are not members of a class. Only
member functions have a this pointer.
#include <iostream>
using namespace std; int main(void) {
class Box { Box Box1(3.3, 1.2, 1.5); // Declare
public: box1
// Constructor definition Box Box2(8.5, 6.0, 2.0); // Declare
Box(double l = 2.0, double b = 2.0, double box2
h = 2.0) {
cout <<"Constructor called." << endl; if(Box1.compare(Box2)) {
length = l; cout << "Box2 is smaller than
breadth = b; Box1" <<endl;
height = h; } else {
} cout << "Box2 is equal to or larger
double Volume() { than Box1" <<endl;
return length * breadth * height; }
}
int compare(Box box) {
return 0;
return this->Volume() > box.Volume();
}
}
private:
double length; // Length of a box //Output
double breadth; // Breadth of a box Constructor called.
double height; // Height of a box Constructor called.
};
Member dereferencing operators
We used the pointer variable to get the memory address
of a variable (used together with the & reference
operator). However, you can also use the pointer to get
the value of the variable, by using the * operator (the
dereference operator):

string food = "Pizza"; // Variable declaration


string* ptr = &food; // Pointer declaration
// Reference: Output the memory address of food with the
pointer (0x6dfed4)
cout << ptr << "\n";
// Dereference: Output the value of food with the pointer
(Pizza)
cout << *ptr << "\n";
Operators Precedence
• Operator precedence determines the grouping of
terms in an expression. The associativity of an operator
is a property that determines how operators of the
same precedence are grouped in the absence of
parentheses. This affects how an expression is
evaluated. Certain operators have higher precedence
than others; for example, the multiplication operator
has higher precedence than the addition operator:
• For example x = 7 + 3 * 2; here, x is assigned 13, not 20
because operator * has higher precedence than +, so
it first gets multiplied with 3*2 and then adds into 7.
• Here, operators with the highest precedence appear
at the top of the table, those with the lowest appear at
the bottom. Within an expression, higher precedence
operators will be evaluated first.
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right
Typecast operators
Type Casting is a mechanism which enables a variable
of one datatype to be converted to another
datatype.When a variable is typecast into a different
type, the compiler basically treats the variable as of the
new data type.

type (expression) //functional casting

double x = 10.3;
int y;
y = int (x); // functional notation

(type) expression //c-like casting


Array
Definition of Array : An array is a sequence or
collection of the related data items that share
a common name.
Purpose : To store multiple values in a single
variable but of same data type.
Syntax : datatype
arrayname[dim1][dim2]….[dimn];
where dimension indicates number of slots.
e.g. int x[5]; => This indicates one dimensional
array with 5 slots.

1 2 3 4 5
x
❑Memory Requirement
Total no of bytes required for any array
can be calculated as follows,
bytes = size of given data type *
dim1*dim2*….*dimn.
e.g. int x[5] => bytes = 2*5=10
int y[5][3] => bytes = 2*5*3=30
There are mainly two types of the array:
• One – Dimentional array
• Two – Dimentional array
❑One – Dimentional Array:
A list of items can be given one variable
name using only one dimension and such a
variable is called a one dimensional array.
Syntax:
datatype array-name[size];
Ex: int a[5];
• To access particular slot
syntax: arrayname[logical slotno]
e.g. a[0]- content of 0th slot(logical)
If & is placed before the array name with slot
no then it indicates the address of
corresponding slot.
Initialization of one – dimentional arrays:
⮚ After an array is declared, its element must
be initialized. Otherwise, they will contain
“garbage”. An array can be initialized at
either of the following stages:
1. At compile time
2. At run time
1. Compile time initialization:
Syntax:
Type array-name[size] = {list of values};
The value in the list are separed by commas.
Ex: int a[3] = {0,0,0} ;
int a[3] = {10, 20, 30, 40} ; will not
work. It is illegal in C.

Ex: int counter[] = {1,1,1,1}


counter array contain four element with
initial value 1.
2. Run time initialization :
An array can be explicitly initialized at run
time. This approach is usually applied
for initializing large arrays.
Ex:
for(i=0; i<100 ; i++)
{
if (i < 50 )
sum[i] = 0.0;
else
sum[i] = 1.0;
}
Ex: int x[3];
scanf (“%d%d%d”, &x[0], &x[1], &x[2] ) ;
Will initialize array elements with the values
entered through the keyboard.
❑ TWO – DIMENTIONAL ARRAY:
If you want to store data into table or matrix form at
that time you can use the two dimensional array.
Declaration of two dimentional array:
Syntax : data_type array-name[dim1][dim2];

Where dim1 indicates total rows and dim2


indicates total columns.
Ex: ITEM 1 ITEM2 ITEM 3
SALES MAN 1 310 275 365
SALES MAN 2 210 190 325
SALES MAN 3 405 235 240
SALES MAN 4 260 300 380
Memory representation of the two dimentional
array for v[4][3] .
column 0 column 1 column2

[0][0]
310 275 [0][1]36 [0][2]
Row 0 5
[1][0] [1][1] [1][2]
10 190 325
Row 1
[2][0] [2][1] [2][2]
405 235 240
Row 2
[3][0]
310
[3][1] [3][2]
275 365
Row 3
Initializing two dimentional array:
Ex: int table[2][3] = {0,0,0,1,1,1};
int table[2][3] = {
{0,0,0},
{1,1,1}
};
Initializing two dimentional array:
When the array is completely initialized
with all values, we need not specify the
size of the first dimension. That is, the
statement is permitted.
int table[][3] = {
{0,0,0} ,
{1,1,1)
};
If the value is missing in an initializes, they
are automatically set to zero.
Ex: int table[2][3] ={
{1,1} ,
{2}
};
int m[3][5] = { 0, 0 };
or
int m[3][5] = { {0} , { 0} };
Thank You

You might also like