OOPS Introduction
OOPS Introduction
OOPS Introduction
OBJECT
OBJECT ORIENTED
ORIENTED
PROGRAMMING
PROGRAMMING WITH
WITH C+
C+
++
B.R.MOHAN
CSE DEPT
SSE, MUKKA
OOC
Text Book
1. Object oriented Programming with C++,
Sourav Sahay, Oxford Press, 2006
(chapters1-10)
Reference Books
1. C++ Primer, Stanley Lipmann, Josee Lajoie,
Barbara E. Moo, 4th Edition, Addison Wesley,
2005
Unit-1:
1. Introduction to C++
2. Class and Object
Unit-2:
3. Class & Objects contd.
Unit-3:
4. Dynamic Memory Management
5. Constructors and Destructors
OOC
Unit-4:
6. Inheritance
Unit-5:
7. Virtual Functions & Dynamic
Polymorphism
8. Stream Handling
Unit-6
9. Stream Handling contd 10. Operator
Overloading
OOC
Unit-7:
11. Operator Overloading contd.
Unit-8:
12. Type Conversion, New style
casts, and RTTI
13. Templates FT,CT, STL
14. Exception Handling
OOC
Procedural Languages –
Pascal, C, Basic, Fortran are
examples of procedural languages.
lays emphasis on executing a set of
instructions.
-Get some input
-Add these numbers
-divide by 6
-display the results
OOC
Accessible by
Global Variable
any function
Accessible by Accessible by
Function A Function B
Function A Function B
GlobalData Global Data Global Data Global Data
Fn A Fn A Fn A Fn A
Hence we need a way to restrict the access to the data ,
to hide it from all but a few critical functions. This protects the
data, simplifies the maintainence and other benefits.
Object Oriented Approach
Idea of Object Oriented Language – data
and the functions that access the data are
combined into a single unit called OBJECT.
An objects functions are called Member
functions in C++.
MFs provide only way to access data.
OOC
object
Data
MF
MF
Object Object
Data
Data
MF
MF
MF
MF
OOC
Corporate Paradigm
Sales Manager
Secretary
Finance
Dept
Personnel
Dept
Personnel Data
Finance Data
Personnel Manager
Finance Manager
Personnel Staff
Financial Assistant
OOC
Feature C
Specifications for class
Circle
Object1 Object2 Object3
Class Circle
Feature A Feature B
Class Circle Class Circle
Feature A Feature B Feature A Feature B
Feature C
Feature C Feature C
OOC
Class Data1
Data2
Data3
Data
Function
Fn1
Fn2
Fn3
OOC
Class can contain private and public.
Usually the data within the class is private and the functions that
operate on data are public so that they can be accessed from outside
the class. Fig- for public & private
Class
Not accessible private
From outside
Class
Data or Functions
Accessible from
Outside class public
Data or Functions
OOC
Differences between
C and C++
In C, u may / may not In C++, you must
Include function include function
Prototypes prototypes.
C++ lets you
specify default
values for
function‘s
parameters
OOC
Eg-
void myfunction(int
In C, x=3,int y=4)
the declaration In C++, u may
Of a variable must place the
be at the beginning variable declara
Of the function tions close to
the statements
that use
variables before
using it in a
statement
OOC
Lab Program-1
• Steps :
1. Define an Employee class and declare the given data members.
2. Get the employee details using the member function
3. calculate netsalary of given employee using formula
display the resultant value
4. write the main function and create Employee objects. Call
member functions on the employee objects to read the data ,to
calculate netsalary and to print the data members
Class:
• The class is a fundamental OOP concept in C++.
• A class declaration defines a new type that links
code(functions/operations) and data.
• This new type is then used to declare objects of that class.
OOC
Syntax:
class name objectname
object name.datamember; //access class members
object name.datamember; //calling mf on an object
Access specifiers:
public: allows fns / data to be accessible to other parts of ur
Prg
private: by default fucntions and data declared within a class
are private to that class and may be accessed only by public
members of the same class.
OOC
Member functions
void employee::getdata() { //get emp details}
void employee::computenetsal() {
da=0.52*basic;
gross=basic-da;
it=0.3*gross;
//compute netsal
netsal=basic+da-it;
}
OOC
Void employee::display()
{
//display employee info on the monitor
}
OOC
Steps-
1. Define a student class and declare the given data
members
2. Get the student details using member function-
getdata()
3. Find average of 2 better marks for each student
4. Display the resultant values-usn, name and
average marks of all students
5. Write a main() & create an array of 10 student
objects. Call mfs of student objects to read data,
to calculate average marks & print the
student details along with their avg mks
OOC
Lab Program-3
• Write a C++ program to create a class called
COMPLEX and implement following overloading
functions ADD that return a COMPLEX number.
i) ADD(a,s2) - where a is an integer (real part)
and s2 is a complex number.
ii) ADD(s1,s2) – where s1, s2 are complex
numbers
OOC
Friend Function
If u want to explicitly grant access to a
function that is not a member of current class,
declare that function a friend inside the class /
structure declaration.
Friend declaration occurs inside the class
because compiler reads class definition, size and
behaviour of data type
OOC
Friend Functions
It is possible to grant nonmember function access
to the private members of a class by using a friend.
Friend function has access to all private and
protected members of the class for which it is a friend.
To declare a friend , include its prototype within
the class, preceding it with keyword friend
OOC
OBJECT ORIENTED
PROGRAMMING WITH C++
REVIEW OF STRUCTURES
OOC
But if d=28;
m=2;
y=1999;//28th Feb 1999
and we call the function as
Again if d=31;
m=12;
y=1999;//31th Dec 1999
nextday(&d1,&m1,&y1); //ok
nextday(&d1,&m2,&y2); //incorrect set passed
//beginning of dateuser.c
#include “date.h”
void main()
{ struct date d;
d.d=28; d.m=2; d.y=1999;
nextday(&d);
…
} //end of dateuser.c
OOC
Drawback/Disadvantage
1. Data is not secure and can be manipulated by
any function/procedure.
2. Associated functions that were designed by
library programmer don’t have rights to work
upon the data.
3. They are not a part of structure definition itself
because application program might modify
the structure variables by some code
inadvertently written in application program
itself
OOC
OOPS Features –
1. Inheritance 2.
Polymorphism
OOC
Polymorphism
Function Prototyping
• FP is necessary in C++.
• C++ strongly supports function prototypes
• Prototype describes the function’s interface to the
compiler
• Tells the compiler the return type of function, number ,
type and sequence of its formal arguments
OOC
Eg-
class Distance
{
int iFeet;
float fInches;
public:
void setFeet(int); //only member function
int getFeet(); //prototypes are given
void setInches(); //in the class definition.
float getInches();
};
OOC
class Distance
{
int iFeet;
float fInches;
public:
void setFeet(int); //only member function
int getFeet(); //prototypes are given
void setInches(); //in the class definition.
float getInches();
};
OOC
#include<iostream.h>
#include “Distance.h”
void main()
{Distance d1,d2;
d1.setFeet(2); d2.setInches(2.2);
d1.setFeet(3); d2.setInches(3.3);
cout << d1.getFeet() << “ “ << d1.getInches();
cout << d1.getFeet() << “ “ << d2.getInches(); }
}
OOC
After
Struct Distance
{
int iFeet;
float fInches;
};
OOC
After -
void setFeet( Distance * const int);
OOC
Before –
void getFeet()
After –
void getFeet(Distance * const );
Before –
void setInches( float);
After –
void setInches(Distance * const, float);
Before –
float getInches();
After –
float getInches(Distance * const);
OOC
Before –
void Distance :: setFeet ( int x)
{
iFeet = x;
}
After –
void setFeet( Distance * const this, int x)
{
this -> iFeet = x;
}
OOC
Before –
Before –
void Distance :: setInches (float y)
{ fInches = y; }
After –
Void setInches(Distance * const this, float y)
{
this -> fInches = y;
}
OOC
Before –
float Distance :: getInches ()
{ return fInches; }
After –
void getInches(Distance * const this)
{
return this -> fInches;
}
OOC
Before –
D1.setFeet(1);
After -
setFeet(&d1, 1);
Before –
d1.setInches(1.1);
After –
setInches(&d1 , 1.1);
OOC
Before –
cout << d1.getFeet() << endl;
After –
cout << getFeet(&d1) << endl;
Before –
cout << d1.getInches() << endl;
After –
cout << getInches(&d1) << endl;
In case of C++, dot operator’s
definition is extended
Its evident that ‘this’ pointer should
OOC
{
int iFeet;
float fInches;
public:
void setFeet(int); //only member function
int getFeet(); //prototypes are given
void setInches(); //in the class definition.
float getInches();
Distance add( Distance);
};
Distance add( Distance dd) OOC
{ Distance temp;
temp.iFeet = iFeet+dd.iFeet;
temp.fInches=fInches+ dd.fInches;
return fInches;
}
described conversion for this add() using this ptr
temp
Temp.iFeet
iFeet
Temp.fInches Data in temp is
fInches assigned to d3
using temp in
add(d2) function
d3=d1.add(d2);
d1
d2
iFeet
iFeet
fInches
fInches
To
Class A
{
Public:
void show();
};
Class B
{
Public:
void show();
};
OOC
Class Distance
{ int iFeet, fInches; //private by default
Public:
void setFeet(int x)
{ iFeet =x; }
int getFeet() { return iFeet; }
Void setInches(float y) { return fInches; }
float getInches() { return fInches; }
};
OOC
//meminline.cpp
Class A
{
public:
void show();
};
Inline void A :: show() //definition in header file
{
//definition of A :: show() function
}
Inline member Functions
OOC
Class Distance
{ int iFeet; float fInches;
public:
void setFeet(int);
int getFeet() const; //constant function
void setInches(float);
float getInches() const; //constant function
Distance add(Distance) const; //constant function
};
void Distance::setFeet(int x) OOC
{ iFeet=x; }
void Distance::getFeet() const //const function
{ iFeet++; //ERROR!!
return iFeet; }
void Distance::setInches(float y)
{ fInches=y; }
void Distance::getInches() const //const function
{ fInches=0.0; //ERROR!!
return fInches;
}
void Distance::add(Distance dd) constOOC//const function
{
Distance temp;
temp.iFeet= iFeet + dd. iFeet;
temp.setInches (fInches + dd.fInches);
iFeet++; //ERROR!!
return temp;
}
For const. member functions, memory occupied by invoking
object is a read-only memory. Only const. member functions can
be called with respect to constant objects.
However nonconstant functions can be called with respect to
nonconstant objects.
OOC
Class A //mutable.h
{
int x;
mutable int y;
public:
void abc() const //a constant member function
{ //error: cant modify a non-constant da
x++; //ta member in a const. mf
y++;//ok can modify a mutable data member in
} // const. mf
void def() //non-const. mf
{ x++; //ok can modify nonconstant data member
//in a non-const. mf
y++; //ok can modify mutable data member in a
//nonconst.mf } };
/*end of mutable.h*/
OOC
Friend Functions
• Friend keyword should appear in the prototype only and
not in the definition
• Since it is a nonmember function of the class of which it
is a friend, it can be prototyped in either private or public
section of the class.
• A friend function takes 1 extra parameter compared to a
member function that perform a same task
• No need of using scope resolution operator for defining a
member function.
OOC
Friend Classes
• A class can be friend of another class. Member
Functions of a friend class can access private data
members of objects of class of which it is a friend.
If class B is made a friend of class A, example illustrates this
Class A
{friend class B; //declaring class B as a friend of class A
/* rest of class A*/ //doesn’t matter to declare in priv or
//public section for friend function
};
fig- declaring friend classes
OOC
Class B
{ A * Aptr;
Public:
Void B :: test_friend(int i)
{
Aptr -> x=i; //accessing private data member
}
Class B; //friendtran.cpp
Class C;
Class A
{
friend class B;
int a;
};
Class B
{
friend class C;
};
OOC
Class C
{
void f( A *p)
{
p->a++; //error: C is not a friend of A despite
// being a friend of friend
}
};
//end of friendtran.cpp
Class A
{
/*rest of class A
Friend void B :: test_friend();
};
To compile this code successfully, compiler should first
see definition of class B, else it doesn’t know that
test_friend() is a member function of class B.
However, a pointer of type A * is a private member of
class B.
This problem of circular dependence is solved by
forward declaration by inserting a line
Class A; //Declaration ,only not definition!!
before definition of class B. declarations and
definitions of 2 classes appear in next slide.
OOC
//Friendmemfunc.h
class A;
class B
{
A *Aptr;
Public:
void Map(const A * const);
void test_friend(const int=0);
};
class A
{
int x;
public:
friend void B :: test_friend ( const int=0)
};
Forward declaring a class that requires a friend.
OOC
Class A;
Class B
{
A *Aptr;
public:
void map(const A *A);
void test_friend(const int =0);
};
Class A
{int x;
Public: friend void B:: test_friend(const int =0);
}; inline void B:: test_friend( const p)
{
Aptr->x=p;
}
OOC
#define SIZE 3
/*A class to duplicate the behavior of an integer array*/
class A
{
int iArray[SIZE];
Public:
void setElement (unsigned int,int);
int getElement (unsigned int);
};
/*function to write the value passed as a second parameter
OOC
void main()
{ A Aobj; //Ambiguity error due to multiple definitions of A
}
Code showing a reference to a globally declared class can lead to
ambiguity error.
/*A2.h*/
namespace A2
{
class A
{ };
} /*end of namespace A2.h*/
OOC
The 2 definitions of class are enveloped in 2 different
Namespaces.
Corresponding namespaces, followed by SRO, must be
prefixed
to the class name while referring to It anywhere in the source
code. Hence the ambiguity encountered in above listing can be
overcome.
Revised definition of main() function
#include “A1.h”
#include “A2.h”
void main()
{ A1::A Aobj1; //ok: Aobj1 is an object of class defined in A1.h
A2::A Aobj2; //ok: Aobj2 is an object of class defined in A2.h
} enclosing classes in namespaces prevent pollution of
namespaces
Qualifying the name of the class with OOC
that of the Namespace
can be cumbersome.
The using directive enable us to make class definition inside
A namespace visible so that qualifying the name of referred
Class by name of namespace is no longer required. Code below
tells how this is done
/*using.cpp*/
#include “A1.h”
#include “A2.h”
void main()
{ using namespace A1;
A1::A Aobj1; //ok: Aobj1 is an object of class defined in A1.h
A2::A Aobj2; //ok: Aobj2 is an object of class defined in A1.h
} using directive makes qualifying of referred class names by
names of enclosing namespaces unnecessary
OOC
name_space a_very_very_long_name
{ class A
{ };
}
void main()
{a_very_very_long_name::A A1; //cumbersome long name
} Assigning a suitably short alias to such a long name solves the
problem
/*longname2.cpp*/
name_space a_very_very_long_name
{ class A { };
}
namespace x=a_very_very_long_name;
/*longname2.cpp*/ OOC
name_space a_very_very_long_name
{ class A { };
}
namespace x=a_very_very_long_name;
Void main()
{
X::A A1; //convenient short name
}
OOC
Aliases – provide an incidental benefit also. If alias name has been used at a
number of places in the source code. Changing the alias declaration so that it stands as
an alias for a different namespace will make each reference of enclosed class refer to a
completely different class
Namespace x=N2;
Then all existing qualifications of referred class names that use x would now
refer to a class A i.e. contained in namespace N2.
OOC
Class A /*nestpublic.h*/
{
public:
class B
{/* definition of class B*/
};
/*definition of class A*/
}; A public nested class
OOC
{
public:
class B
{ public:
void BTest(); //prototype only
}; //definition of class A
}
#include “nestclassdef.h”
void A::B::BTest()
{ //definition of A::B::BTest() function
}
/* definition of rest of functions of class B*/
Code Defining member functions of nested classes
OOC
A nested class may be only prototyped within its enclosing
class and defined later. Again , name of enclosing class with
SRO is required.
Class A /nestclassdef.h
{ class B; //prototype only
};
Class A::B
{ /*definition of the class B*/
}
Defining a nested class outside the enclosing class.
Objects of nested class are defined outside the member functions
of the enclosing class followed by SRO(scope resolution
operator) A::B B1; line will compile only if class B is
defined within public section of class A, else compile
time error occurs
OOC
Class A
{
class B
{
public:
void ATest();
};
}; //nestclassobj.cpp
#include “nestclassobj.h”
void A::ATest()
{ B1.BTest();
B B2;
B2.BTest();
} Declaring objects of nested class in the member functions of the
enclosing class
Member functions of the nested class can
OOC
access the nonstatic public
members of the enclosing class through an object, a pointer, or a reference
only.
//enclclassobj.h
Class A
{
Public:
void ATest();
class B
{
public:
void BTest();
void BTest1();
};
};
OOC
//enclclassobj.cpp
#include “enclclassobj.h”