0% found this document useful (0 votes)
21 views92 pages

OOP Unit1 For Students

The document provides a comprehensive overview of Object Oriented Programming (OOP), covering its foundations, characteristics, and advantages over procedural programming. It discusses key concepts such as classes, objects, inheritance, polymorphism, encapsulation, and abstraction, along with practical examples in C++. Additionally, it highlights the importance of generic programming and memory management in OOP.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views92 pages

OOP Unit1 For Students

The document provides a comprehensive overview of Object Oriented Programming (OOP), covering its foundations, characteristics, and advantages over procedural programming. It discusses key concepts such as classes, objects, inheritance, polymorphism, encapsulation, and abstraction, along with practical examples in C++. Additionally, it highlights the importance of generic programming and memory management in OOP.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 92

Object Oriented Programming

Unit I : Foundation of Object Oriented Programming (08


Hrs)
⮚Introduction to procedural, modular, object-oriented and generic programming techniques. Limitations of
procedural programming, Need of object-oriented programming
⮚ fundamentals of object-oriented programming:
◦ objects, classes, data members, methods, messages, data encapsulation
◦ data abstraction and information hiding, inheritance, polymorphism.
⮚Inline functions, Function overloading
⮚Call by value and call by reference, return by reference
⮚functions with default arguments, this pointer
⮚illustrative Simple C++ Programs.
⮚Dynamic initialization of variables, memory management operators
⮚Member dereferencing operators, operator precedence, typecast operators, Scope resolution operators, arrays.
2
Procedure oriented programming

3
Procedural programming technique
• Pascal ,FORTRAN , C - Procedural languages

• Problem is viewed as things to be done – calculating, printing

• Number of functions for actions to be performed

• Technique of hierarchical decomposition

• In multi-function programs, global data may be accessed by all functions

• Function may have its own local data

4
5
6
Characteristics of procedure oriented
programming
• Focus on algorithms(actions)

• Large programs are broken into smaller programs-functions

• Most functions share global data

• Data move freely from one function to other

• Functions change global data

• Employs top - down design approach

7
Limitations of Procedural programming
• Global data are very vulnerable to changes

• Changes in any data structure requires changes in functions using that


structure
• Bugs may creep in

• Procedural languages does not model real world problems very well.

8
Modular programming

9
Modular programming
• Modularity is added to procedural programming

• high-level decomposition of the code of an entire program into pieces

• Adding functionally independent modules

• Every module focuses on achieving only one aspect of desired functionality

10
Object oriented programming
paradigm

11
Object Oriented Programming
Object oriented programming is an approach that provides a way of
modularizing program by creating partitioned memory area for both data and
functions that can be used as template for creating copies of such modules on
demand.

12
Object oriented programming
• Treats data as critical element

• Program development does not allow it flow freely around the


system
• It ties data with functions operating on the data and protects it from
accidental modification from outside functions
• Decomposition of problems into small entities called objects
• Data of objects can be accessed only by the functions associated
with the data.
• Functions of one object can access functions of other objects

13
Striking features of OOP
• Emphasis on data than functions

• Program is divided into small entities-objects

• Functions and data are tied together

• Data is hidden and cannot be accessed by external functions

• Objects may communicate with each other through functions

• Bottom–up design approach

14
Need of Object Oriented Programming
• Break down requirements into objects with responsibility, not into functional
steps
• Easier to model real world problems

• To make software projects more manageable and reliable

• Code reusability

• Data protection

15
Generic programming
The method of Generic Programming is implemented to increase the efficiency of the code. Generic
Programming enables the programmer to write a general algorithm which will work with all data
types. It eliminates the need to create different algorithms if the data type is an integer, string or a
character.

The advantages of Generic Programming are

1.Code Reusability

2.Avoid Function Overloading

3.Once written it can be used for multiple times and cases.

16
Fundamental concepts of Object
oriented programming

17
OOP Fundamentals
⮚Class
⮚Objects
⮚Abstraction
⮚Encapsulation
⮚Inheritance
⮚Polymorphism
⮚containment
⮚Dynamic binding
⮚Message passing
18
Structure in C

19
Class in C++

20
Classes (data members and methods )
Classes-:

• The entire set of code and data of an object can be made a user defined data type
with the help of a class.

• It is expanded concept of structure in C.

• Instead of holding only data , classes can hold both functions and data

• Variable declared inside the class is known as data member

• The function inside the class is known as member function or member methods.

21
Objects
Objects-:
Objects are variables of type class.
e.g. fruit mango.

We can create any number of objects to the class

22
What is an object?

An object is a software entity that mirrors the real world in some way. It is a basic
run time entity, may represent a person, a place, a bank account or any item.
A software object in OOP has data (the attributes) and code that responds to
instructions.
code and data as being welded together --the code completely wrapping the data in
a shell to protect it from the hostile outside world."
Reusable software component
”An object has state, behavior, and identity.”
“An object is an encapsulation of state (data values) and behavior (operations).
Thus an object is in many ways similar to a module, or an abstract data type."
[Budd]
23
object
• State of an object includes current values of all its attributes

• Attribute can be static or dynamic

• Behavior is how object acts and reacts in terms of state change and message
passing
• E.g. calsal() is behavior of employee object

• Identity is state of object at given instant of time

24
Representing objects

25
Message passing
• OOP consists of set of objects that communicate with each other

• Objects communicate with each other by sending and receiving information

• Objects communicate through functions

26
27
Abstraction

• Abstraction – natural mapping and association of data and functions which operate
on data.

• Abstraction is the process of identifying key aspects of entity and ignoring others

• Only imp aspects to current scenario

• e.g. person object for healthcare industry, payroll system

• Data abstraction or behavioral abstraction

28
Encapsulation
• Encapsulation- Hide or unhide part of data or functionality from some
components.
• Used to hide data, implementation details, internal structure of an object

• Interaction with object is through public interface

• E.g. TV remote and buttons are interfaces for it

• Data hiding leads to security

29
Inheritance
• It is the process by which objects of one class acquire the properties of
objects of another class .
• Hierarchical classification.

• Helps in handling complexity

• Is-a kind of hierarchy

• Manager and salesperson class inherit all features of employee class

30
31
Polymorphism
• It means the ability to take more than one form.

• Ability of different types of related objects to respond to the same message

• Operator overloading, function overloading.

• Draw method for shape class

32
33
Benefits of Object oriented
programming

34
Benefits of OOP
• Through inheritance , we can eliminate redundant code and extend and reuse
existing code
• We can write code with modules communicating with each other which leads
to time saving and higher productivity
• Software complexity can be managed

35
Applications of OOP
• Most popular applications is user interface design as Windows

• Real business systems containing more objects and complex methods

• Simulation and modeling

• Object oriented database

• Hypertext, hypermedia

• AI expert systems

• Neural networks and parallel programming

• CAD/CAM systems

36
An Example of C++ class
• Binding data and functions operating on that data

• Class is user defined data type

• Variables-objects

37
#include<iostream>
using namespace std;
void person :: display(void)
class person
{ cout<< “\n name is:”<< name;
{
char name[30]; cout<< “ \n age is:” << age;
int age; }
public:
void getdata(void); int main()
void display(void);
{
};
person p1;
void person :: getdata(void)
p1.getdata();
{ cout<<“Enter person name”;
cin >> name; p1.display();
cout<<“Enter age”; return 0;
cin>> age; } }

38
• Member function are generally public

• Objects are used to invoke functions in that class

• Basic class supports abstraction and encapsulation

39
Structure of C++ program
Typical C++ program consists of four sections which can be placed in separate code files and
then compiled independently or jointly

• Include files

• Class declarations

• Member function definition

• Main program

40
Defining member functions and inline
functions

41
Defining Member Functions
Member functions defined outside class
◦ Binary scope resolution operator (::)
◦ “Ties” member name to class name
◦ Uniquely identify functions of particular class
◦ Different classes can have member functions with same name
◦ Format for defining member functions
ReturnType ClassName::MemberFunctionName( ){

}
◦ Does not change whether function public or private

Member functions defined inside class


◦ Do not need scope resolution operator, class name
◦ Compiler attempts inline
◦ Outside class, inline explicitly with keyword inline

42
43
Inline Functions
Inline functions
◦ Keyword inline before function
◦ Function expanded inline when invoked
◦ Asks the compiler to copy code into program instead of making function call
◦ Reduce function-call overhead
◦ Compiler can ignore inline
◦ inline is request to compiler, not command
◦ Good for small(1/2 lines of function), often-used functions

Example
inline double cube( const double s )
{ return s * s * s; }
◦ const tells compiler that function does not modify s

44
Making an Outside Function Inline
inline void rate1::setdata(int x, int y)
{
a=x;
b=y;
}

45
Function overloading

46
Function Overloading
Function overloading
◦ Functions with same name and different parameters
◦ Should perform similar tasks
◦ I.e., function to square ints and function to square floats
int square( int x) {return x * x;}
float square(float x) { return x * x; }
Overloaded functions distinguished by signature
◦ Based on name and parameter types (order matters)
◦ Name mangling
◦ Encodes function identifier with parameters
◦ Type-safe linkage
◦ Ensures proper overloaded function called

47
Function Overloading

48
Function Overloading

49
Function Overloading

50
Call by value, call by reference

51
Call by value
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().

52
Call by value
int main()
{
int data = 3;
change(data);
cout << "Value of the data is: " << data<< endl;
return 0;
}
void change(int data)
{
data = 5;
}

53
Call by Reference
If a formal parameter is a reference parameter
◦ It receives the memory address of the corresponding actual parameter

A reference parameter stores the address of the corresponding actual parameter


During program execution to manipulate data
◦ The address stored in the reference parameter directs it to the memory space of the corresponding
actual parameter

54
Call by Reference
In call by reference, original value is modified because we pass reference
Reference parameters can:
◦ Pass one or more values from a function
◦ Change the value of the actual parameter
Reference parameters are useful in three situations:
◦ Returning more than one value
◦ Changing the actual parameter
◦ When passing the address would save memory space and time

55
Call by Reference

56
Return by reference

57
return by reference

58
return by reference
max( a , b) = -1;
If a is larger -1 is assigned to it.
If b is larger -1 is assigned to it.

59
Functions with default arguments

60
Default Arguments
Function call with omitted parameters
◦ If not enough parameters, rightmost go to their defaults
◦ Default values
◦ Can be constants, global variables, or function calls
Set defaults in function prototype
int myFunction( int x = 1, int y = 2, int z = 3 );
◦ myFunction(3)
◦ x = 3, y and z get defaults (rightmost)
◦ myFunction(3, 5)
◦ x = 3, y = 5 and z gets default

61
This pointer

62
This pointer in C++
• Every object has access to its own address through this pointer

• inside a member function, this may be used to refer to the invoking object

63
class Employee {
void display()
public:
{
int id; //data member (also instance variable)
cout<<id<<" "<<name<<" "<<salary<<endl;
string name; //data member(also instance variable)
}
float salary;
};
Employee(int id, string name, float salary)
{
this.id = id;
this.name = name;
this.salary = salary; }

64
Dynamic initialization of variables

65
Declaration of variable
In C we need to declare variables at the beginning of scope level
C++ allows variable declaration anywhere in program, even right at the place of
its first use.

66
Declaration of variable
Allowed anywhere

67
Dynamic Initialization of Variables
Initialization at run time

int n =strlen("abc");
float a=3.142 * r * r;

float average; // declare where it is necessary


average = sum/I;
float average = sum/I; // initialize dynamically at run time.

68
Member dereferencing operators

69
Member Dereferencing Operator
C++ permits us to define a class containing various types of data & functions as members.
C++ also permits us to access the class members through pointers. C++ provides a set of three
pointer to member operators.

70
Memory management opearators

71
Memory Management Operator
• We use dynamic allocation techniques when it is not known in advance how
much of memory space is needed.
• C++ supports two unary operators new and delete that perform the task of
allocating & freeing the memory.
• An object can be created by using new and destroyed by using delete.
• A data object created inside a block with new, will remain in existence until it
is explicitly destroyed by using delete.

72
Memory Management Operator
new
1) Can be used to create objects of any
type pointer-variable = new data_type;
int *p=new int;
2) We can initialize the memory ,
Pointer-variable = new data-type(value);
int *p=new int(25);
3) can be used to create a memory space for any data type including
user-defined types such as arrays, structures and classes,
int *p = new int[100]; int *q = new int[n];

73
new
The new operator has following advantages over the function malloc() in c -.

i) It automatically computes the size of the data object. No need to use sizeOf()

ii) If automatically returns the correct pointer type, so that there is no need to
use a type cast.

iii) new and delete operators can be overloaded.

iv) It is possible to initialize the object while creating the memory space.

74
Memory Management Operator
Continue…
Delete
1) Used to release memory space,
delete pointer variable;
delete p;
2) Used to free a dynamically allocated array,
delete [size]pointer variable;
delete [ ]p;

75
Typecasting

76
The Cast Operator

• Type conversion
• (type-name) expression; //C notation
• Type-name (expression) //C++ notation

77
Type casting
• Conversion of one data type to other

• Implicit and explicit

• Explicit type conversion is referred to as cast(uses casting operator)

• Explicit cast allows programmer to suspend type check

78
Implicit conversion
Does not require operator
Compiler
short num1=200;
float num2;
num2=num1;
num1 has been converted from short to int
int a=10; char b= ‘A’;
int c=a+b;
Allows short to int, int to float
Some conversions may imply loss of precision and compiler signs warning, which can be avoided by explicit
conversion

79
Explicit cast : C style
C Style : compatibility

Using bracketed name of the required type before variable to be casted


int num1;
float num2=3.14f;
num1=(int) num2;

80
Explicit cast : C++ style
• const_cast

• static_cast

• dynamic_cast

• reinterpret_cast

81
const_cast
used to cast away constness of variable
const_cast can be used in programs that have any object with some constant
value which need to be changed occasionally at some point.
const_cast < new_type > ( expression )
const int val=5;
const int*ptr= &val;
int *ptr1=const_cast<int *> ptr;

82
static_cast
Any conversion which compiler performs implicitly can be made explicit using
this operator
Compile time cast
Warning msg for loss of precision are turned off
double dval;
int ival;
ival=dval; // implicit
ival=static_cast <int>(dval);

83
static_cast
char c;
int *p1=(int *)(&c); //c style cast will allow this
*p1=3; //ok at compile time, fails at run time

int *p2 = static_cast <int *> (&c); // compile time error

Thus staic cast is more restrictive for unsafe casting

84
Scope resolution opeartor

85
Scope Resolution Operator
C++ is a block - structured language. The scope of the variable extends from the point of its declaration till the end of
the block containing the declaration.
{ int x = 1;
===
}
{ int x = 2;
} =====
The two declaration of x refer to two different memory locations containing different values.
Blocks in c++ are often nested. Declaration in a inner block hides a declaration of the same variable in an outer block.
In C, the global version of a variable cannot be accessed from within the inner block. C++ resolves this problem by
using scope resolution
operator (::), because this operator allows access to the global version of a variable.

86
# include<iostream.h >
int m = 10;
int main ( ) The output of program is
{int m = 20; k = 20
{ m = 30
int k = m; :: m = 10
int m = 30; m = 20
cout << “K = “<<k; :: m =10
cout << “m = “<<m; In the above program m is declared at three places.
cout << “: : m = “<< : : m;
And ::m will always refer to global m.
}
cout << “m = “<< m;
cout << “::m =“ <<::m;
}
return 0; }

87
Arrays

88
Arrays

• Array application in C++ is similar to that of C


• Exception is the way character arrays are initialized
• When initializing char in ANSI C ,compiler allows to declare array size as exact length
of the string constant
• char string [3]=“xyz”;
• But in CPP size should be one larger than number of string characters
• char string[4]=“xyz”;

89
Arrays within Class
const size 100
Class array
{
int a[size];
int n;
public:
void getdata();
void disp();
void search();
};
90
Memory Allocation for Objects

91
Array of Objects
To create Multiple objects of same class
Example : Array of Employees
employee e[100];

92

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy