OOP Unit1 For Students
OOP Unit1 For Students
3
Procedural programming technique
• Pascal ,FORTRAN , C - Procedural languages
4
5
6
Characteristics of procedure oriented
programming
• Focus on algorithms(actions)
7
Limitations of Procedural programming
• Global data are very vulnerable to changes
• Procedural languages does not model real world problems very well.
8
Modular programming
9
Modular programming
• Modularity is added to procedural programming
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
13
Striking features of OOP
• Emphasis on data than functions
14
Need of Object Oriented Programming
• Break down requirements into objects with responsibility, not into functional
steps
• Easier to model real world problems
• 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.
1.Code Reusability
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.
• Instead of holding only data , classes can hold both functions and data
• 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.
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
• Behavior is how object acts and reacts in terms of state change and message
passing
• E.g. calsal() is behavior of employee object
24
Representing objects
25
Message passing
• OOP consists of set of objects that communicate with each other
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
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
29
Inheritance
• It is the process by which objects of one class acquire the properties of
objects of another class .
• Hierarchical classification.
30
31
Polymorphism
• It means the ability to take more than one form.
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
• Hypertext, hypermedia
• AI expert systems
• CAD/CAM systems
36
An Example of C++ class
• Binding data and functions operating on that data
• 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
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
• 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
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
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;
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.
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
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
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
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
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