OOPs 1
OOPs 1
OOPs 1
with C++
Prepared by
ALOK KUMAR
MCA-2012
Part – A
1. Overview of OOP
Object Oriented Paradigm
• Software Evolution
• Evolution of Programming Paradigm
- Monolithic
- Procedure Oriented Programming
- Structured Oriented Programming
- Object Oriented Programming
Structured Vs Object Oriented
Programming
Function Oriented Object Oriented
Procedure Abstraction Procedure & Data abstraction
Does not support Supports External Interface
External Interface
Free flow of Data Secured Data & not freely
flows
Also called FOP Also called OOP
Elements of OOP
Well suited for:
• Modeling the real world problem as close as
possible to the users perspective.
• Interacting easily with computational
environment.
• Constructing reusable software components
and easily extendable libraries.
• Easily modifying and extending
implementations of components without
having to recode every thing from scratch.
Elements of OOP
Definition of OOP:
“Object oriented programming is a
programming methodology that associates
data structures with a set of operators which
act upon it.”
Elements of OOP
• Objects
• Classes
• Encapsulation
• Data Abstraction
• Inheritance
• Polymorphism
• Dynamic Binding
• Message Passing
Objects
• OOP uses objects as its fundamental building
blocks.
• Objects are the basic run-time entities in an
object-oriented system.
• Every object is associated with data and
functions which define meaningful operations
on that object.
• Object is a real world existing entity.
• Object is anInstance of a particular class.
Object
Operation
Operation
Example: StudentObject
Enroll()
st_name
st_id
Performa Displayinfo()
branch
nce()
semester
Result()
Class
• Class is a collection of similar objects.
Class
Encapsulation
“Mechanism that associates the code and the
data it manipulates into a single unit and
keeps them safe from external interference
and misuse.”
Encapsulation
Class: student
Functions: Enroll()
Displayinfo()
Result()
Performance()
Data Abstraction
“A data abstraction is a simplified view of an
object that includes only features one is
interested in while hides away the
unnecessary details.”
Point
Line
Polymorphism
• Polymorphism means that the same thing can
exist in two forms.
+
Dynamic Binding
“ Dynamic Binding is the process of linking of
the code associated with a procedure call at
the run-time”.
Message Passing
“The process of invoking an operation on an
object. In response to a message the
corresponding method is executed in the
object”.
Message Passing
StudentObject FacultyObject
Performance
MgmtObject Performance
Result
Object Oriented Languages
1. Object-Based programming Languages
Not support Inheritance & Dynamic Binding
Example: Ada
Include Files
Class Definition
int main() {
Starts definition of special function
main()
cout << "Hello World\n";
output (print) a
string
return 0;
Program returns a status
} code (0 means OK)
Preprocessing
Temporary file
C++ (C++ program) C++
Preprocessor Compiler
Executable
C++ Program Program
C++ LANGUAGE
C++ Program is a collection of
• Tokens
• Comments
• White Space
C++ TOKENS
RESERVED KEYWORDS
IDENTIFIERS
LITERALS
OPERATORS
SEPARATORS
RESERVED KEYWORDS
• Programmer-designed tokens
• Meaningful & short
• Long enough to understand
• C++ rules for Identifiers
- alphabets, digits, underscore
- should not start with digits.
- Case sensitive
- Unlimited length
- Declared anywhere
LITERALS
Control
stmt
If contin
If switch while do for break
ue
return
else
Arrays in C++
• An array is a consecutive group of memory
locations.
• An array is a collection of similar data
elements.
Memory and Arrays
Each int is 2 bytes 16 bits
a[0]
a[1]
int a[6];
a[5]
Array Initialization
We can initialize an array :
NOTE:
Need not have to specify a size when initializing,
the compiler will count automatically.
An array printing function
{
A[0][0]
char A[4][3]; A[0]
A[0][1]
A[0][2]
A[1][0]
{
A[1][1]
A is an array of size 4. A[1]
A[1][2]
A[2][0]
A[2][1]
{
Each element of A is A[2]
A[2][2]
A[3][0]
an array of 3 chars A[3][1]
A[3]
{
A[3][2]
2-D Array
return(sum/NumHW);
}
C++ Strings
• Supports C-String
• C++ defines a string class called string
• The string class supports several constructors.
The prototypes of commonly used one is
– string( );
ex: string str("Alpha");
C++ Strings
Operator Meaning
= Assignment
+ Concatenation
+= Concatenation assignment
== Equality
!= Inequality
< Less than
<= Less than or equal
> Greater than
>= Greater than or equal
>> Reads
<< Prints
C++ Strings
• str2 = str1; // assigning a string
• str3 = str1 + str2; //concatenating strings
• if(str2 > str1) cout<<” str2 is bin“;//compares
• str1 = "This is a null-terminated string.\n";
• cin>>str1; //reads
• Cout<<str1; //prints
3. Modular Programming with
Functions
Modular Programming
“The process of splitting of a large program into
small manageable tasks and designing them
independently is known as Modular
Programming or Divide-&-Conquer
Technique.”
C++ Functions
• “Set of program statements that can be
processed independently.”
ceil floor
Etc.,
Function parameters
• The Formal parameters are local to the
function.
{
int a = y;
cout << a << endl;
}
cout << a << endl;
}
Nested Blocks
void example()
{
for (int j=0;j<10;j++)
{
int k = j*10;
cout << j << “,” << k << endl;
{
int m = j+k; k j
cout << m << “,” << j << endl;
m
}
}
}
Storage Class
• Each variable has a storage class.
– Determines the life time during which
the variable exists in memory.
– Some variables are created only once
• Global variables are created only once.
– Some variables are re-created many
times
• Local variables are re-created each time a
function is called.
Storage Classes
• auto – created each time the block in which
they exist is entered.
• register – same as auto, but tells the
compiler to make as fast as possible.
• static – created only once, even if it is a
local variable.
• extern – global variable declared
elsewhere.
Argument Passing
• Pass by Value
• Pass by Reference
• Program to swap two numbers
• Program to sort list of numbers
Inline Functions
“ Inline functions are those whose function body
is inserted in place of the function call
statement during the compilation process.”
• Syntax:
inline return_dt func_name(formal parameters)
{
function body
}
Inline Functions
• Frequently executed interface functions.
Data members
Members functions
};
Class Specification
• class Student
{
int st_id; Data Members or Properties of
Student Class
char st_name[];
void read_data(); Members Functions or
Behaviours of Student Class
void print_data();
};
Class Specification
• Visibility of Data members & Member functions
public - accessed by member functions and all
other non-member functions in the
program.
private - accessed by only member functions of the
class.
protected - similar to private, but accessed by
all the member functions of
immediate derived class
default - all items defined in the class are private.
Class specification
• class Student
{
int st_id;
char st_name[]; private / default
void read_data(); visibility
void print_data();
};
Class specification
• class Student
{
public:
int st_id;
char st_name[]; public visibility
public:
void read_data();
void print_data();
};
Class Objects
• Object Instantiation:
The process of creating object of the type class
• Syntax:
class_name obj_name;
ex: Student st;
St_id, St_name
void read_data( )
void print_data( )
Class Object
• More of Objects
ex: Student st1;
Student st2;
Student st3;
Class Objects
st1 st2
55, Mary
void read_data( )
void print_data( )
st3
33, Joseph
Class Objects
• Array of Objects
void read_data( )
S[0]
ex:print_data(
Student s[8]; S[1]
void )
S[2]
St[0]
24, Sakshi S[3]
void read_data( )
S[4]
S[5]
void print_data( )
S[6]
St[4] S[7]
Accessing Data Members
(outside the class)
• Syntax: (single object)
obj_name . datamember;
ex: st.st_id;
• Syntax:(array of objects)
obj_name[i] . datamember;
ex: st[i].st_id;
Accessing Data Members
(inside the class member function)
• Syntax: (single object)
data_member;
ex: st_id;
• Syntax:(array of objects)
data_member;
ex: st_id;
Defining Member Functions
• Syntax :(Inside the class definition)
ret_type fun_name(formal parameters)
{
function body
}
Defining Member Functions
• Syntax:(Outside the class definition)
ret_type class_name::fun_name(formal parameters)
{
function body
}
Accessing Member Functions
• Syntax: (single object)
obj_name . Memberfunction(act_parameters);
ex: st.read( );
• Syntax:(array of objects)
obj_name[i] . Memberfunction(act_parameters);
ex: st[i].read( );
Data Hiding
• “Data hiding is the mechanism of
implementation details of a class such a way
that are hidden from the user.”
private:
st_name
Cal_best() st_id Print_data()
branch
semester
Result()
Data Hiding
• The access specifier acts as the key strength
behind the concept of security.
emp1 emp2
55, Mohn
static int emp_seq;
void read_data( )
void print_data( )
emp3
Static Member Functions
• Member functions that are declared with
static specifier.
Synatax:
class class_name
{
public:
static ret_dt fun_name(formal parameters);
};
Static Member Functions
Special features:
• They can directly refer to static members of the
class.
• They does not have this pointer.
• They cannot be a static and a non-static version
of the same function.
• The may not be virtual.
• Finally, they cannot be declared as const or
volatile.
Scope Resolution Operator
int i; // global i
void f()
{
?
int i; // global i
int i; // local i void f()
i = 10; // uses local i {
Solution…..
. int i; // local i
::i = 10; // now refers to global i
. .
. .
} .
}
Scope Resolution Operator
• The :: operator links a class name with a
member name in order to tell the compiler
what class the member belongs to.
If Instances of
void read_data( )
void print_data( )
=
same
Class!!
void read_data( )
void print_data( )
emp1 emp2
Passing Objects as Arguments
st
ptr 2FCD54
Pointers to Objects
“Pointers can be defined to hold the address
of an object, which is created statically or
dynamically”.
33, Joseph Statically created object:
student *stp;
void read_data( )
stp = &st;
void print_data( )
Dynamically created object:
student *stp;
st stp = new student;
2FCDA4
Pointers to Objects
• Accessing Members of objects:
Syntax:
ptr_ob j member_name;
ptr_obj memberfunction_name( );
Example:
stp st_name;
stp read_data ( );
The this Pointer
“The this pointer points to the object that
invoked the function”.
void read_data( )
st
2FCD54
Pointer to Class Member
“A special type of pointer that "points"
generically to a member of a class, not to a
specific instance of that member in an
object”.
Outside Class:
ret-type class-name::operator#(arg-list)
{
// operations
}
Operator Overloading
Example:
comp comp::operator+(comp op2 )
{
comp temp;
temp.real = op2.real + real;
temp.img = op2.img + img;
return temp;
}
Operator Overloading
Implicitly passed
by this pointer
Explicitly passed
ob1 = ob1 + ob2; argument
• Example:
istream& operator >>(istream&
in, Matrix& m)
{
for(int i=0; i<row*col; i++)
void main()
{ {
in >> Mat[i];
} :
Cin>>mobj;
return in;
:
}
}
Overloading <<
• Prototype:
friend ostream& operator <<(ostream&, Matrix&);
• Example:
ostream& operator <<(ostream&
out, Matrix& m)
{
for(int i=0; i<row; void
++i)
main()
{ {
for(int j=0; j<col; : j++)
cout<<mobj;
{ out>> Mat[i][j] >> : “\t”
; }
}
out << endl;
Program for Implementation
• Pgm to create a class Matrix assuming its properties
and add two matrices by overloading + operator.
Read and display the matrices by overloading
input(>>) & output(<<) operators respectively.
Point
Line
Inheritance
Fruit
Polygon
Triangle Rectangle
Polygon Inheritance
Triangle RightAngle
Triangle
Base Class
• “Base class is a class which defines those
qualities common to all objects to be derived
from the base.”
• Example:
class CRectangle: public Cpolygon{ };
class CTriangle: public Cpolygon{ };
Inheritance & Access Specifier
• Example:
class Orange: Acess_specifier Yellow,
Acess_specifier Red
{ };
Inheriting Multiple Base Classes
Yellow Red
Orange
Constructors, Destructors & Inheritance
• Constructor functions are executed in their
order of derivation.
Mango
Malgoba Mallika
Mango Mango
Constructors, Destructors & Inheritance
• When an object of a derived class is created,
if the base class contains a constructor, it will
be called first, followed by the derived class'
constructor.
• Syntax:
derived-constructor(arg-list) : base1(arg-list),
base2(arg-list), … baseN(arg-list)
{ // body of derived constructor }
Passing Parameters to Base-Class Constructors
using
access declaration
Granting Access
• using statement:
is designed primarily to support namespaces.
• Access declaration:
restores an inherited member's access
specification
Syntax:
base_class_name::member;
Granting Access
• Access declaration is done under the
appropriate access heading in the derived
class’ declaration.
Note:
No type declaration is required.
Granting Access
class base {
public:
int j;
};
j k
2 copies
i
j&k
Hierarchy of Classes
Remedy…..?
Virtual Base Classes
• Used to prevent multiple copies of the base
class from being present in an object derived
from those objects by declaring the base class
as virtual when it is inherited.
• Syntax:
class derived : virtual public base
{ . . . };
Virtual Functions
• “A virtual function is a member function that
is declared within a base class and redefined
by a derived class.”
• Example:
class base {
public:
virtual void member_func(){ }
};
Virtual Functions
Base Virtual function
Derived1 Derived2
override override
Virtual Functions
• When accessed "normally" virtual functions
behave just like any other type of class
member function.
Derived1 override
Derived2 override
Virtual Functions Are Hierarchical
• Virtual functions are also hierarchical in
nature.
Derived1 override
Derived2
Virtual Functions Are Hierarchical
Base Virtual function
Derived1 Derived2
override
Pure Virtual Functions
• “A pure virtual function is a virtual function
that has no definition within the base class.”
Program
Inserts
Output Streams Into
Output output
Device stream
I/O Stream Classes for console Operations
ios
iostream
istream_withassign ostream_withassign
iostream_withassign
C++'s Predefined Streams
When a C++ program begins execution, four built-
in streams are automatically opened.
• get(), getline(),read()
Output Operator
• Insertion Operator:(<<)
• float var;
char line[20];
cout<< var<<line;
• put(),putline(),write()
Overloading >> operator
• Prototype:
friend istream& operator >>(istream&, Matrix&);
• Example:
istream& operator >>(istream&
in, Matrix& m)
{
for(int i=0; i<row*col; i++)
void main()
{ {
in >> Mat[i];
} :
Cin>>mobj;
return in;
:
}
}
Overloading << operator
• Prototype:
friend ostream& operator <<(ostream&, Matrix&);
• Example:
ostream& operator <<(ostream&
out, Matrix& m)
{
for(int i=0; i<row; void
++i)
main()
{ {
for(int j=0; j<col; : j++)
cout<<mobj;
{ out>> Mat[i][j] >> : “\t”
; }
}
out << endl;
Formatted I/O
• There are three related but conceptually
different ways that we can format data.
Files Program
Inserts
Output Streams Into
output
stream
Write data
I/O Stream classes for File operations
ios
streambuf
istream ostream
filebuf
iostream
ifstream ofstream
fstream
fstreambase
I/O Stream Class Hierarchy
Opening & Closing a File
• Opening (default mode):
–Create a file stream
–Link it to the filename
–Two method to Open a file
• Using constructor function of the class
• Using member function open() of the class
• Closing
–Delinking the file stream from filename
Using constructor of the class
• ofstream out(“data.txt”);
• ifstream in(“data.txt”);
in
Read data
Input Stream
data.txt Program
out
Write data
Output Streams
Using member function open()
of the class
• creating a filestream for writing
ofstream out;
out.open(“result.txt”,ios::app);
• closing a file
– out.close( );
– in.close( );
Modes of File Opening
Parameter Meaning
ios::in opens file for reading only
ios::out opens file for writing only
ios::app opens file for appending at the end only
ios::binary opens file in binary mode
ios::trunc Deletes the content of the file if it exists
ios::ate opens file for appending but at
anywhere
File Pointers
• Each file has two associated pointers
– get pointer : to reads from file from given location
– put pointer : to writes to file from given location
• Manipulation of get pointer
– seekg: moves get pointer to a specified location
– tellg: gives the current position of the get pointer
• Manipulation of put pointer
– seekp: moves put pointer to a specified location
– tellp: gives the current position of the put pointer
Moving to a specified location in file
• Syntax:
– seekg(n_bytes); //can be + or – n bytes
– seekg(n_bytes, reposition);
• repostion constants:
– ios::beg
– ios::cur
– ios::end
NOTE:
+ go forward by n bytes
- go backwards by n bytes
Error Handling with Files
• File which we are attempting to open for
reading does not exist.
• The filename used for a new file may already
exist.
• attempting an invalid operation such as
reading past the eof.
• attempting to perform an operation when a
file is not opened for that purpose.
Function Return value & meaning
eof() returns true (non-zero) if end-of-file
encounterd while reading
otherwise false(zero)
fail() returns true when an iput of output operation
has failed
bad() returns true if an invalid operation is
attempted of any unrecoverable error as
occurred. if it false it may possible to recover
from any other error reported and continue
operation
good() returns true if no error has occurred, if it false ,
no further operations can be carried out.
8. Exception Handling
Introduction
• Exception: “An abnormal condition that
arises in a code sequence at run time”.
• Syntax:
catch (type argument)
{
// catch block
}
try
{
Program statements
requires monitor for exceptions
}
catch( type argument )
{
Program statements
handles for Exception
}
try
{
Program statements
requires monitor for exceptions
}
catch( type1 argument )
{ catch( type2 argument )
{ catch( typen argument )
Program statements{
handles for Exception
Program statements
handles for Exception
Program statements
} handles for Exception
}
}
Using try & catch
try
{
Arithmetic
int d = 0;
int a = 30 / d; throws Exception
}
catch(int e )
{
printf("Division by zero.");
}
Exception Handling Fundamentals
NOTE:
Throwing an unhandled exception causes
the standard library function terminate()
to be invoked. By default, terminate()
calls abort() to stop your program.