Unit 1 - Fundamental of OOP - Final
Unit 1 - Fundamental of OOP - Final
Unit 1 - Fundamental of OOP - Final
Syllabus:-
Introduction to object-oriented programming, Need of object-oriented programming,
Fundamentals of object-oriented programming: Namespaces, objects, classes, data
members, methods, messages, data encapsulation, data abstraction and information hiding,
inheritance, polymorphism. Benefits of OOP, C++ as object oriented programming
language.
Machine level Language : (ASCII code 0100 0001 represent letter A’’)
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.
.The first high-level programming languages were designed in the 1950s. Now there are dozens
of different languages, including Ada , BASIC, COBOL, C, C++, JAVA, FORTRAN, LISP, Pascal, and
Prolog
1. Unrestricted Access:-
Program structure become more difficult.
Program become difficult to modify.
Changes made to global data item may need rewriting all functions that access that items.
2. Provide a poor model of the real world
Attributes
for people, eye color and job title;
for cars, horsepower and number of doors
Behavior
something a real-world object does in response to some stimulus.
If you apply the brakes in a car, it will generally stop
Object Oriented Programming
• The basic reason for the innovation of OOP
is to remove the flaws/drawbacks of
Procedural approach.
• OOP treats data as a critical element
and does not allow it to flow freely around
the system.
• It ties data closely to the functions
that operate on it, and does not allow
access to the outside functions.
• Data of one object can not be accessed
• OOP divides a problem into the by the functions of other object.
number of objects, then build data However, functions of one object can
and function around these objects. The be accessed by the functions of other
data of an object can be accessed by only object.
those functions which are associated with
the same object.
POP Vs OOP
Procedure Oriented Programming Object Oriented Programming
Divided Into In POP, program is divided into small In OOP, program is divided into parts
parts called functions called objects.
Approach POP follows Top Down approach. OOP follows Bottom Up approach.
Access POP does not have any access specifier. OOP has access specifiers named
Specifiers Public, Private, Protected, etc.
Data In POP, Data can move freely from In OOP, Data of an object can be
function to function in the system. accessed only by those functions
which are associated with the same
object.
POP Vs OOP
Procedure Oriented Programming Object Oriented Programming
Expansion To add new data and function in POP is OOP provides an easy way to add new
very difficult. data and function.
Data Access In POP, Most function uses Global data In OOP, data can not move easily from
for sharing, that can be accessed freely function to function, it can be kept
from function to function in the public or private so we can control the
system. access of data.
Data Hiding POP does not have any proper way for OOP provides Data Hiding using
hiding data so it is less secure. private access specifier, so provides
more security.
• Data and functions of the object are tied together in data Structure
called Class/Object.
Result Account
Bank Account
• Object (Attributes and
Operations):
OBJECT: CAR
Attributes (Properties)
Manufacturer Operations (Actions)
Model Start
Color Drive
Year Park
Price
• Object (Attributes and
Operations):
Vehicle
▪ If the operands are strings, then the operation would produce a third
string by concatenation.
Poly Morphism Polymorphism
(Many) (Forms) (Many Forms)
Principles of OOP
• Polymorphism:
Principles of OOP
• Message Passing:
“The process of invoking an operation on an object. In response to a
message the corresponding method is executed in the object”.
StudentObject FacultyObject
MgmtObject
Performance
Result
Principles of OOP
• Data Members:
Data members include members that are declared with any of the fundamental types,
as well as other types, including pointer, reference, array types, bit fields, and user-
defined types.
Principles of OOP
• Methods:
Methods are functions that belongs to the class.
There are two ways to define functions that belongs to a class:
1. Inside class definition. 2. Outside class definition.
class Example
class Example {
{ int a,b;
public: public:
void add() //method defined inside class void add(); //method declared inside class
{ };
------ void Example::add() //method defined outside class
------ {
} ------
}; }
int main() int main()
{ Example obj; { Example obj;
obj.add(); obj.add();
return 0; return 0;
} }
Principles of OOP
• Namespaces:
A namespace is a declarative region that provides a scope to the identifiers (the
names of types, functions, variables, etc) inside it.
Namespaces are used to organize code into logical groups and to prevent name
collisions that can occur especially when your code base includes multiple libraries.
Here,
std is the namespace where ANSI C++ standard class libraries are defined.
Benefits & Applications of
OOP
Benefits of OOP
Reusability
We can use single code many time in our entire application. This is done with
the use of a class.
Data Redundancy
This can mean two different fields within a single database or two different
spots in multiple software environments or platforms. Whenever data is
repeated, it basically constitutes data redundancy
Benefits of OOP
Code Maintenance
This feature is more of a necessity for any programming language, it helps users
from doing re-work in many ways. It is always easy and time-saving to maintain
and modify the existing codes by incorporating new changes into them.
Security
With the use of data hiding and abstraction mechanism, we are filtering out
limited data to exposure which means we are maintaining security and
providing necessary data to view.
Design Benefits
Object-Oriented Programs force the designers to have a long and extensive
design phase, which results in better designs and fewer flaws.
Benefits of OOP
Better Productivity
This leads to more work done, finish a better program, having more inbuilt
features, and easier to read, write and maintain.
Encapsulation
Encapsulation is used to hide the values or state of a structured data object
inside a class, preventing unauthorized parties’ direct access to them.
Polymorphism
Polymorphism is the ability of an object to take on many forms. The most
common use of polymorphism in OOP occurs when a parent class reference is
used to refer to a child class object
Applications of
OOP
User interface design such as windows, menu.
Real-Time Systems
Simulation and Modeling.
Object-oriented databases
AI and Expert System
Neural Networks and parallel programming
Decision support and office automation systems etc.
Syllabus:-
int main ()
{
// global variable g
cout << g;
// Local variable g
g = 20;
cout << g;
return 0;
}
C++ is Partially OOPL
Availability of Friend function:
Friend Class A friend class can access private and protected members of other class
in which it is declared as friend.
It is sometimes useful to allow a particular class to access private members of other class.
Therefore, again the Object oriented features can be violated by C++.
C++ Program Structure
#include<iostream>
using namespace std;
class Example
{
//Class declaration, if any along with its member variables and functions
};
//global variables, if any
int main() //This is where the execution of program begins
{
//code
return 0;
}
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World";
return 0; Hello World
}
Basic Input / Output
Standard Output (cout)
• The cout object in C++ is an object of class ostream. It is used to display the output to
the standard output device i.e. monitor.
1.cout << "Output sentence"; // prints Output sentence on screen
2.cout << 120; // prints number 120 on screen
3.cout << x; // prints the content of x on screen
/* This is a comment */
/* C++ supports single-line and multi-line comments. All characters available inside any
comment are ignored by C++ compiler. */
#include <iostream>
Enumerations are used to define symbolic using namespace std;
constants(called an enumerator) enum direction {East, West, North, South};
Each enumerator is a constant whose type is the int main()
{
enumeration. direction dir = North;
To define an enumeration, keyword enum is used. cout<<dir<<endl;
cout<<East;
enum enum-name { list of names } var-list; return 0;
e.g. enum direction {East, West, North, South};
}
Output: 2
0
C++ Data Types
User Defined Data Types- typedef
Examples:
int a;
float mynumber;
int a, b, c;
Scope of variables
Control structures
C++ has only three kinds of control structures, which we refer to as control statements:
Sequence statement
“sequence is a series of statements that executes one after another”
Conditional structure
If Statement
If-else
Nested if-else
Else if ladder
Switch statement
if(a==b)
{
if(b==c)
cout << “a, b, and c are the same”;
}
else
cout << “a and b are different”;
Control structures
else...if Ladder
if(Expression1)
{
variable = Expression2;
}
else
{
variable = Expression3;
}
Since the Conditional Operator ‘?:’ takes three operands to work, hence they are also called ternary operators
Iteration structures (loops)
for Loop
This loop generally used if you don’t know how many times you want to do something
before you start the loop?
#include <iostream>
using namespace std;
int main()
{
int i = 2 ;
i =i-1;
while(i)
{
cout<<"its a while loop";
i++ ;
}
return 0;
}
Iteration structures (loops)
do-while Loop
This loop places the test expression at the end of the loop.
When we want to guarantee that the loop body is executed at least once, even if test condition is
false.
break and countinue statement
The break statement
The break statement takes you out of the bottom of a loop.
The continue statement
Go back to the top of the loop when something unexpected happens .
Arrays and Strings
An array as a collection of variables of the same type.
In an array collection of items stored at contiguous memory locations
Elements of an array can be accessed randomly using indices of an array.
Syntax:
type arrayName [ arraySize ];
Example:
22 47 12 21 33 60 Arrays Elements
0 1 2 3 4 5 Arrays Indices
Array Length : 6
First Index: 0
Last Index: 5
Arrays and Strings
Initializing Arrays
int main()
{
int a[5];
int i;
for(i=0;i<5;i++)
{
cout<<“\n Enter Element:”;
cin>>a[i];
}
for(i=0;i<5;i++)
cout<<“\n”<<a[i];
return 0;
}
2D - Arrays
double sales[DISTRICTS][MONTHS];
Accept array elements from user and display it.
int main()
{
int a[3][4];
int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<4;j++)
{
cout<<“\nEnter Element:”;
cin>>a[i][j];
}
}
for(i=0;i<3;i++)
for(j=0;j<3;j++)
cout<<“\n”<<a[i][j];
return 0;
}
C++ Strings
C++ provides following two types of string representations:
1. The C-style character string.
2. Strings that are objects of the string class.
The C-style character string originated within the C language and continues to be
supported within C++.
This string is actually a one-dimensional array of characters which is terminated by
a null character '\0'.
Example:
char greeting[] = "Hello";
C String-Manipulation Functions
In order to manipulate null terminated strings header file <cstring> is included in the program. This header
file provides the same functionality as string.h in C.
Example
Class and Data Abstraction
void display() {
#include <iostream>
cout<<"a = " <<a << endl;
using namespace std;
cout<<"b = " << b << endl;
}
class implementAbstraction
};
{
private:
int main() {
int a, b;
implementAbstraction obj;
obj.set (10, 20);
public:
obj.display ();
return 0;
// method to set values of
}
// private members
void set(int x, int y)
OUTPUT:
{
a= 10
a = x;
b= 20
b = y;
}
We are not allowed to access the variables a and b directly, however one can call the function set() to set
the values in a and b and the function display() to display the values of a and b.
Separating Interface from Implementation
//Cal.cpp
// implementation of functions
Functions are used to perform certain actions, and they are important for reusing
code: Define the code once, and use it many times.
The function’s code is stored in only one place in memory, Even though the function is
executed many times in the course of the program.
Three steps..
A. Function declaration/ function prototype
B. Function definition
C. Function call
Functions in C++
Experience has shown that the best way to develop and maintain
large programs is to construct it from smaller pieces(Modules)
This technique is Called “Divide and Conquer”.
Bad Development Approach Wise Development Approach
main()
main()
{
{
}
-----
-----
. function f1()
{
.
---
----
}
-----
Return 0; function f2()
} {
---
}
Function Declaration/ Function Prototype
1) It states the return type of the data that the function will return.
2) It states the number of arguments passed to the function.
3) It states the data types of the each of the passed arguments.
4) It states the order in which the arguments are passed to the function.
Syntax
– Parameter list
• Comma separated list of arguments
• Data type needed for each argument
• If no arguments, use void or leave blank
– Return-value-type
• Data type of result returned (use void if nothing returned)
Function Definition
Example function
int square( int y )
{
return y * y;
}
return keyword
– Returns data, and control goes to function’s caller
If no data to return, use return;
– Function ends when reaches right brace
Control goes to caller
Functions cannot be defined inside other functions
Function Calling
Calling/invoking a function
– sqrt(x);
– Parentheses an operator used to call function
• Pass argument x
• Function gets its own copy of arguments
– After finished, passes back result
Function Example
cout << endl; called. When done, it returns the result.
return 0; // indicates successful termination
} // end main
1 4 9 16 25 36 49 64 81 100
Parameter Passing Technique
Actual Parameters:
The values/variables passed while calling a function are called actual parameters.
Formal Parameters:
These are the variables written/declared in function definition/
prototype, and receive their values when a call to that function is made.
The value(s) of the actual parameters are copied to formal parameters when the call to
that function is made.
Parameter Passing Technique
Example:
int main()
{
int x=10,y=20;
int s = sum(x,y); //Actual Parameters //Statement 2
return 0;
}
In Statement 1, the variables a and b are called FORMAL PARAMETERS. In Statement 2 the arguments x and y are
called ACTUAL PARAMETERS (as they are the actual ones to hold the values, you can think it like this).
Parameter Passing Technique
int main(void)
{
int x = 5, y = 7;
// Passing parameters
func(x, y);
cout << "In main, x = " << x << " y = " << y;
return 0;
}
Parameter Passing Technique
1.While Passing Parameters using call by value , xerox copy of original parameter is created and passed to the called
function.
2.Any update made inside method will not affect the original value of variable in calling function.
1. While passing parameter using call by address scheme , we are passing the actual address of the
variable to the called function.
2. Any updates made inside the called function will modify the original copy since we are directly modifying
the content of the exact memory location.
2. make_pair: It constructs a pair with its first element set to x and its second element set to y.
E.g.
// Initializing the pair with int type
pair <int, int> a;
pair <int, int> b;
a = make_pair (10, 20);
b = make_pair (15.5, 'B'); // conversion takes place from pair<double, char>
o/p a: 10, 20
b: 15, 66
3. move: It moves as rvalue. move is used to indicate that an object may be “moved from”, i.e. allowing the
transfer of resources from an object(to be moved) to another object.
e.g.
string s = "Hello!!"; o/p Hello Hi
string s1 = “Hi";
vector<string> str;
str.push_back (s); // It copies 's' in str
str.push_back (move(s1)); // It moves 's1' in the str(containing 's')
<utility> in C++
4. move (range of elements): It moves the elements in the range [first, last) into the range
beginning at result.
e.g.
string1 = {"Hi", “Hello", “How", "are", “you"};
string2 (5);
// use of move i.e.it moves from first to last element in string 1 to the string2 from it's(string 2)
starting
move ( string1.begin(), string1.begin()+5, string2.begin() );
Inline Functions
Even though the prototypes for friend functions appear in the class definition, friends are
not member functions of the class in which they are declared.
To make a function as a friend of a class, it is declared inside the class either in private or in
public section with keyword friend before its declaration.
Declaration:
class class_name
{
// syntax of friend function.
friend data_type function_name(argument/s);
};
Friend Function
#include <iostream>
using namespace std;
class Box
{
private:
int length;
public:
Box(): length(0) { }
friend int printLength(Box); //friend function declaration
};
int printLength(Box b) //friend function defination
{
b.length += 10;
return b.length;
}
int main()
{
Box b;
cout<<"Length of box: "<< printLength(b)<<endl;
return 0;
} O/P 10
Static Members
Static data members
Static data members are class members that are declared using static keywords
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 initialized before any object of this class is being created, even before main starts.
Static Function Members
A static member function can be called even if no objects of the class exist
the static functions are accessed using only the class name and the scope resolution
operator ::
A static member function can only access
static data member
other static member functions
any other functions from outside the class.
Friend Function
In that case, all the member function of the class declared as friend become
the friend functions of the other class.
Example:
class A
{ Class B is declared as a friend of class A in
friend class B;
the above code.
}; So, now all the member functions of class
class B B became friend functions of class A.
{
};
Function Overloading
Two or more functions can have the same name but different
parameters
Example:
They do not have return types, not even void and they cannot return values.
They cannot be inherited, though a derived class can call the base class
constructor.
Default Constructor
Parameterized constructors
Overloaded constructors
Constructors with default argument
Copy constructors
Dynamic constructors
Default constructor
This will enable the system to allocate the right amount of memory for
each object when the objects are not of the same size.
Multiple Constructors in a Class
C++ permits to use more than one constructors in a single class.
Add( ) ; //No arguments
Add (int, int) ; // Two arguments
A destructor never takes any argument nor does it return any value.
It will be invoked implicitly by the compiler upon exit from the program – or
block or function as the case may be – to clean up storage that is no longer
accessible.