SlideShare a Scribd company logo
1 of 136
Download to read offline
OOP/AKN/Part_II/1
Object Oriented Programming
Concepts
Part II
Ajit K Nayak, Ph.D.
SOA University
OOP/AKN/Part_II/2
Contents
 Object Oriented Concepts
 Class & Objects
 Constructor & Destrctors
 Operator Overloading
 Friend function
 Data Conversion
 This pointer
 Friend class
 Nested Class
OOP/AKN/Part_II/3
How to Solve a Complex System?
 The Technique of mastering complexity has
been known since ancient times “Divide and
Rule” …Dijkstra
i.e Decomposition of the Problem
 Intelligent decomposition directly addresses
the inherent complexity of software by forcing
a division of systems state space
…Parnas
OOP/AKN/Part_II/4
Decomposition
 Algorithmic/Functional Decomposition
1. Divide the system to some modules
2. Each module should denote a major step
in overall process.
 Object Oriented Decomposition
1. View the world as a set of autonomous
agents that collaborate to perform some
higher level behaviour.
OOP/AKN/Part_II/5
Functional Decomposition
The System
Function1 Function2 Function3
Function11 Function12
. . . . . .
. . . . . .
. . . . . .
OOP/AKN/Part_II/6
OO Decomposition
Autonomous Agents(Objects)
Agent3
Agent1
Agent4
Agent2
msg1
msg2
msg4
msg3
OOP/AKN/Part_II/7
Functional decomposition
Main
Problem: No. of words in a file
getWordFromFile addToWordList
getWordList sortword checkWord
Sorted Words
Word List Flag
Words Words(prev,curr)
WordWord Words
getSortedWordList countDiffWords printResult
Sorted Words
Sorted Words
Count
Count
OOP/AKN/Part_II/8
OO Decomposition
Problem: No. of words in a file
File
WordList
getWord
Autonomous Agents(Objects)
OOP/AKN/Part_II/9
Which is the Right way?
 Algorithmic view highlights the ordering of
events
 Object Oriented view emphasizes the agents
(objects) that either cause action or to be
acted upon
 Both The Philosophy are important
 If the system is Very large, Complex, to be
Extended, Maintained then choose OO
approach.
OOP/AKN/Part_II/10
Procedural Programming
 With procedural programming,
you are able to combine
sequences of calling statements
into one single place.
 A procedure call is used to invoke
the procedure. After the
sequence is processed, flow of
control proceeds right after the
position where the call was made
.
Main
Program
Procedure
OOP/AKN/Part_II/11
 Now a program can be viewed as a
sequence of procedure calls.
 The main program is responsible to pass
data to the individual calls, the data is
processed by the procedures and the
resulting data is presented.
 Thus, the flow of data can be illustrated as a
hierarchical graph, a tree.
Procedural Programming
OOP/AKN/Part_II/12
Procedure Program view
Main Program
Data
Procedure1
Procedure2 Procedure3
Procedural Programming uses Algorithms as the
Basic building block.
OOP/AKN/Part_II/13
Features of
Object Oriented Programming
 Abstraction
Encapsulation
 Composition
 Aggregation
 Association
 Inheritance
 Polymorphism
 Dynamic Binding
OOP/AKN/Part_II/14
Abstraction
 An Abstraction denotes the Essential
characteristics of an object that
distinguishes it from all other kinds of
objects and thus defines sharply defined
conceptual boundaries, relative to the
perspective of the viewer.
…Grady Booch
OOP/AKN/Part_II/15
Abstraction
OOP/AKN/Part_II/16
Abstraction(contd.)
 It focuses on the outside view(interface) of an
object. Therefore, it serves to separate an
objects essential behaviour from its
implementation.
 It is used to reduce complexity by ignoring some
aspect of a subject that are not relevant to the
current purpose.
Example : A MAP (is not an exact picture)
 Only the essential features of an area are
shown
 Unimportant features are ignored.
OOP/AKN/Part_II/17
Abstraction(contd.)
 All Abstractions have static as well as dynamic
properties.
Example: A FILE
Static : Name, Size, Content
Dynamic: the value contained in static properties.
 It is dynamic because a file may grow or shrink
in size
 Its name and content may change
OOP/AKN/Part_II/18
Encapsulation
OOP/AKN/Part_II/19
Encapsulation(contd.)
 It is the process of compartmentalising
the elements of an abstraction that
constitute its structure and behaviour.
…Grady Booch
• In this process we keep the properties (or
structure or states) and behaviour of an
object in one place bundeled together.
• It supports information hiding
i.e. hiding all the information that is
unnecessary to the outside world.
OOP/AKN/Part_II/20
Encapsulation
 Encapsulation helps to achieve abstraction by
hiding the implementation of behaviours
 It provides explicit barriers among different
abstractions
Example: Riding a Bike
• Most of the riders are ignorant about the detail
structure of an IC Engine.
• Changing gears on your bike need not require to
know “how the gear mechanism works” just need
to know which lever to move.
OOP/AKN/Part_II/21
 Composition defines a has-a relationship
 An organized collection of components
interacting to achieve a coherent, common
behavior
 The automobile has a windshield.
 It deals with a single, complex system as an
organization of more numerous but simpler
systems
Composition
OOP/AKN/Part_II/22
Composition (examples)
A human being consists of a respiratory
system, a circulatory system, an immune
system, a nervous systems, a skeletal
system, etc
An aircraft consists of a propulsion system, a
control system, a navigation system, etc
An operating system consists of a user
interface, a file system, a network system, a
memory management system, etc
OOP/AKN/Part_II/23
Example: Composition
CPU
Memory
Disk
processorKey Board
Monitor
Mouse
Modem
Aggregation
Association
OOP/AKN/Part_II/24
Plant is a part of Garden(whole) (Association)
Flower is a part of Plant(whole) (Aggregation)
• Garden permits different plants to be raised over
time.
• Replacing a plant does not change the identity of a
garden.
• Removing a Garden does not necessarily destroy all
of its plants
i.e. the life time of Plant(part) and Garden (whole) are
independent.
Example
OOP/AKN/Part_II/25
 Inheritance is the most important is-a kind
of hierarchy
Inheritance helps to share the structure and
behaviour defined in one or more classes
…Grady Booch
i.e a sub-class inherits from one or more
super-classes and subclass is dependent
upon superclass
Inheritance
OOP/AKN/Part_II/26
Inheritance(is a kind of)
OOP/AKN/Part_II/27
Examples (Inheritance)
 Mammal is a kind of Animal
 Tiger is a kind of Mammal
 Cheetah is a kind of Tiger
 House is a kind of Tangible Asset
 Quick sort is a kind of Sorting algo
Sub class?
Super Class?
OOP/AKN/Part_II/28
Examples (contd.)
Vehicle
Land Vehicle Water Vehicle
BoatCar Amphibious Vehicle
OOP/AKN/Part_II/29
Inheritance(contd.)
 It implies a Generalization/Specialization
hierarchy
i.e subclass specializes its superclass and
superclass generalizes its subclass
 Its benefits are
Extensibility,Maintainability,Reusability,
Understandability,Abstraction, and
Substitutability
OOP/AKN/Part_II/30
Polymorphism
 It is the property that allows to exhibit
different behaviours at different situations
 Different objects respond differently to a
same message
Example: message draw
Circle responds with drawing a circle
Polygon responds with drawing a polygon
…
OOP/AKN/Part_II/31
Dynamic Binding
 (Also called as Late binding) Code
associated with a given message will be
decided at run time
 Helps achieving dynamic polymorphism
OOP/AKN/Part_II/32
Object1
Data1+Procedures1
Data Data1 Object3
Data3 + Procedures3
Object2
Data2 + Procedures2
Object4
Data4 + Procedures4
OOP/AKN/Part_II/33
Object-Oriented Programming
 Is a pool of objects. They interact with
each other by passing messages.
 Each object implements its own module.
OOP/AKN/Part_II/34
Object
What we mean?
• Humans understand the world by
viewing it as composed of
autonomous, interacting objects.
• Examples: people, animals, phone,
desks, buildings, stairs, ...
OOP/AKN/Part_II/35
Which is an Object?
An object may be of any of the following
 A Tangible and/or Visible thing
A Table, A Tiger, A Car
 Something that may be apprehended
intellectually
A Bank Account, A Complex Number
 Something towards which thought or action
is directed
A Date, Time
OOP/AKN/Part_II/36
Virtual Objects
Objects that live in programs only, you can
not see by eyes, feel by hand, smell by
nose, and taste by tongue.
Virtual objects are the basic components for
your object-oriented programs.
OOP/AKN/Part_II/37
Examples of Virtual Objects
Bank Account
 Keeps balance; responds to messages to deposit,
withdraw, and get balance
Set
 Elements can be added, deleted, queried for
presence.
GUI Window
 Ultimately responsible for keeping contents of
window. Many operations possible including open,
close, maximize, minimize, move, etc.
OOP/AKN/Part_II/38
Every thing are Objects?
 Some objects may be tangible but have fuzzy
physical boundaries(fog, river) may not
be(sometimes) considered as objects
 Difficult to distinguish my fog from your fog
 But in a weather map; a fog bank over odisha is a distinctly
different object than a fog bank over Maharastra
 Beauty, color, emotions(love, anger) may be
considered as properties of objects rather than
objects.
 A Man(an object) loves his wife(another object)
 The Cat(an object) is gray
OOP/AKN/Part_II/39
Defining an Object
An object has state, behavior, and identity;
the structure and behavior of similar objects
are defined in their common class; the
terms instance and object are
interchangeable
… Grady Booch
OOP/AKN/Part_II/40
State
The State of an object encompasses all of the
properties(static property) of the object plus
the current value (dynamic properties) of
these properties.
… Grady Booch
Example: Object :A-320:IC878 (An Air Craft)
States: Fuel = 1000 lts
Temp = 75 oC
Pressure = 200 lbs
isStart = false
…
Dynamic
PropertiesStatic
Properties
OOP/AKN/Part_II/41
The state
The state shows the existence of an object
When a person is dead, he has no
functions, but their DS is still there if he is
not burnt.
Also called attributes, private space,
member variables, instance variables, data
members, structure of objects etc…
OOP/AKN/Part_II/42
Behavior
Example: Object :A-320:IC878
start(…) : if isstart is false, fuel  x lts, …
run(…) : if isStart is true, …
fly(…) : …
stop(…) : if isStart is true, …
Similarly:
fly causes decreasing in fuel and increasing
in temperature i.e change of states
OOP/AKN/Part_II/43
Behavior
Behavior is how an object acts and reacts,
in terms of its state changes and message
passing.
… Grady Booch
Example: Object :A-320:IC878
start, run, fly, break, stop, turn …
Behavior of an object is influenced by its
state and vice versa
OOP/AKN/Part_II/44
Behavior / Method
A method is an operation an object can make
to respond relevant message.
A method is associated with a class. An
object invokes a method as a reaction to
receipt of a message.
When an object has no method, it is dead!
Also called member functions, operations,
behaviors or services.
OOP/AKN/Part_II/45
Message
A message is a request to an object to
invoke one of its methods. A message
therefore contains
the name of the method and
the arguments of the method.
Consequently, invocation of a method is just
a reaction caused by receipt of a message.
This is only possible, if the method is actually
known to the object.
OOP/AKN/Part_II/46
Message
integer i; /* Define a new object */
i.setValue(1); /* Set its value to 1 */
To express the fact, that the integer object i
should set its value to 1.
The message is “Apply method setValue with
argument 1” (sent to object i). We notate the
sending of a message with the help of .(dot)
OOP/AKN/Part_II/47
Identity
It is that property of an object which
distinguishes it from all other objects
… Grady Booch
Two objects may have same static and
dynamic properties. But the identity
differentiates them
Example:
SSN, EmpID, Slno, …
OOP/AKN/Part_II/48
Object has State Behavior and identity
OOP/AKN/Part_II/49
Class(contd.)
It defines a set of objects that share a
common structure and behaviors
… Grady Booch
A class represents only an abstraction, the
essence of an object. It doesn't exist in time
and space
Example: Class Mammal represents the
characteristics common to all mammals
 To identify a particular Mammal, we say
This Mammal or that Mammal
OOP/AKN/Part_II/50
Examples of class
 Class horse
Structure:
Age
Weight
Color
Behaviour:
Drag
Run
ride
OOP/AKN/Part_II/51
Class
OOP/AKN/Part_II/52
Interface of a Class
 The interface of a class provides its outside view
and therefore, emphasizes the abstraction while
hiding its structure and the secrets of its behavior
 The interface primarily consists of the declarations
of all operations applicable to its instances
 But it may also include the declaration of other
classes, constants, variables and exceptions as
needed to complete the abstraction
OOP/AKN/Part_II/53
Interface(contd.)
 The Interface of a class may be divided
into three parts
1. Public: declaration that is visible to all the
world
2. Protected: declaration that is visible to the
class itself, its subclasses, and its friends
3. Private: declaration that is visible only to
the class itself and its friends.
Also called access specifiers
OOP/AKN/Part_II/54
An Example
class Time{
public:
Time();
void setTime(int,int,int);
void printTime(void);
private:
int hour;
int min;
int sec;
};
Class Name
Attributes / Data
members
Interface
messages /member
functions
Member Access Specifier
OOP/AKN/Part_II/55
Example (contd)
Time::Time(){hour=min=sec=0;}
void Time::setTime(int h, int
m, int s){
hour = h; min=m; sec=s;
}
void Time::printTime(void){
cout<<hour“:”<<min<<“:”<<sec;
cout<<endl;
}
Implementation
Constructor
Operations / Methods /
Member functions
OOP/AKN/Part_II/56
Example (contd)
main(){
Time t;
cout<<“intial time:”;
t.printTime();
t.setTime(13,27,6);
cout<<“after setting time:”;
t.printTime();
}
An Object / Instance
of Time type
Member access
operator
OOP/AKN/Part_II/57
Instantiation
 The mechanism of creating new objects from a
class definition is called instantiation mechanism.
 Every class has such a mechanism.
Static instantiation and Dynamic instantiation.
instantiation at compile time;
instantiation at run time.
 Dynamic instantiation requires a run time support for
allocation and de-allocation of memory.
OOP/AKN/Part_II/58
Structure vs Class in C++
A structure is simply a class whose
members are public by default.
class Time{
int hour;
int min;
int sec;
public:
Time();
void setTime(int,int,int);
void printTime(void);
};
struct Time{
int hour;
int min;
int sec;
public:
Time();
void
setTime(int,int,int);
void printTime(void)};
Public by
default
Private by
default
OOP/AKN/Part_II/59
Other Definitions for Objects
Anything, real, or abstract, about which
we store data and those methods
(operations) that manipulate the data.”
…Martin/Odell
 An object is an instance of a class. It can be
uniquely identified by its name and it defines a
state which is represented by the values of its
attributes at a particular time.
…Peter Müller
OOP/AKN/Part_II/60
Constructors
Constructor is used to initialize(reserves
memory as well as set values to the data
members) an object and it is recognized by
having the same name as the class.
Constructors can be overloaded i.e. there
may be more than one constructors for the
same class with several ways of initialization
Example: Time(), Time(int),
Time(int,int,int), …
OOP/AKN/Part_II/61
Constructors
 Every time an object is created, one constructor
is invoked
 Constructors with no arguments is known as the
default constructor
 Constructor can‟t have a return type
 It should always be declared in public part of the
class structure. (?)
 If no constructor is provided by the programmer
then compiler provides one default constructor.
ClassName(){}
OOP/AKN/Part_II/62
Destructors
 It is a special member function named same as the
class and preceded by a ~
Example:
class Time{
… public:
~Time();
}
 It is used to free the state of an object
 These are called implicitly when an automatic
object goes out of scope. But if an object is
initialized using new than it has to be deleted
 In very unusual situations does the user need to
call a destructor explicitly!
OOP/AKN/Part_II/63
Design a class ComplexNum with Attributes
real (double), img (double) and
Member Functions
Default constructor, parameterized constructor
printComplex, addComplex
Write a main function in which three objects
are created.
Two of them using parameterized constructor, one
using default constructor.
Now add first two objects using addComplex
member function and store the result in third
complex number.
Finally print all the complex numbers.
OOP/AKN/Part_II/64
Complex number Program
class ComplexNum{
private:
double real; double img;
public:
ComplexNum(){real=img=0.0;}
ComplexNum(double r, double i){
real = r; img = i;
}
void printComplex();
ComplexNum addComplex(ComplexNum);
}; // end of class definition
OOP/AKN/Part_II/65
Main Function
main(){
ComplexNum c1(4,5);
ComplexNum c2(3,4);
ComplexNum c3;
c3 = c1.addComplex (c2);
c1.printComplex();
c2.printComplex();
c3.printComplex();
}
OOP/AKN/Part_II/66
Method implementation
void ComplexNum::printComplex() {
cout<<real<<“+ i ”<< img <<endl;
}
ComplexNum ComplexNum:: addComplex(
ComplexNum x) {
ComplexNum z;
z.real = x.real + real;
z.img = x.img + img;
return z;
}
OOP/AKN/Part_II/67
Constant Member Functions
int func(…) const;
 const is a specifier, which specifies that, this
function will not modify the states of an object.
 The value of the object can‟t be changed
 The keyword is written after the parentheses
Example:
class Date{
private:
int d,m,y;
public:
int day()const{return d;}
int month()const{return m;}
OOP/AKN/Part_II/68
Constant Member Functions(contd.)
int year()const;
int addYear(int);
};// end of class definition
int Date::year() const{return y++;}
// Error: Attempt to change value of y
int Date::year() const{return y;}
// Ok
int Date::year() {return y;}
// Error: const keyword missing
int Date::addYear(int a){return y+a;}
// Ok
OOP/AKN/Part_II/69
Constant Member Functions(contd.)
• A constant member function can be invoked for
both constant and non-constant objects.
• A non constant member function can be invoked
only for non-constant objects.
Example:
void f(Date &d, const Date& cd){
int i=d.year(); // Ok (one)
int k=d.addYear(1); // Ok (two)
int l=cd.addYear(1); //Error (two)
int m=cd.year(); //Ok(two)
}
OOP/AKN/Part_II/70
Static Class Members
Static data member is an attribute that is a
part of class, yet is not a part of an object
In other words there is exactly one copy of a
static member instead of one copy per
object
A Function that needs access to members
of a class, yet does not need to be invoked
for a particular object is called static
member function
OOP/AKN/Part_II/71
Example Static data member
class Sclass{
int x, y;
static int z;
. . .
};
int Sclass::z;
main() {
Sclass o, p, q;
}
o
x y
p
x y
q
x y
z
OOP/AKN/Part_II/72
Example: Number of objects that are live in
any point of the program
class Employee{
char* name;
static int count; // static data memb.
public:
Employee(char*);
char* getName();
static int getCount(); // static memb. func
~Employee();
};
OOP/AKN/Part_II/73
Example (contd)
int Employee::count=0;
int Employee::getCount()
{return count;}
Employee::Employee(char* N){
name=new char[strlen(N)+1];
strcpy(name,N);
++count;
}
OOP/AKN/Part_II/74
Example (contd)
Employee::~Employee(){
delete [] name;
--count;
}
char* Employee::getName(){
return name;
}
main(){
cout<<“no of Employees: “<<
Employee::getCount()<<endl;
Employee* e1=new Employee (“Bob”);
Employee* e2=new Employee (“John”);
OOP/AKN/Part_II/75
Example (contd)
cout<<“no of employees: “
<<e1->getCount();
cout<<“Emp1: “<<e1->getName();
cout<<“Emp2: “<<e2->getName();
delete e1;
cout<<“no of employees: “
<<e2->getCount();
delete e2;
cout<<“no of employees: “
<<Employee::getCount();
}
OOP/AKN/Part_II/76
Static Class Members
 Static data members are accessible by both static
and/or non-static member functions
 Static member functions can only access the static
class members
 To access a public static class member, simply
prefix the class name and scope resolution
operator
 To access a private static class member, when no
object exists take help of a static member function
otherwise non-static could be used.
OOP/AKN/Part_II/77
Contents
Operator Overloading
Friend Functions
Data Conversion
Copying Objects
this pointer
Friend class
Nested class
A Complete Example
OOP/AKN/Part_II/78
Overloading Operators
 Operator Overloading allows us to overload the
existing operators s.t. they can have operands as
objects
Complex C=A+B;//A & B are complex number objs
 It doesn't provide any means to create new
operators
 Some operators Can‟t be overloaded
 Binary operators may be overloaded either by a
non-static member function having one argument
or a non-member function having two arguments
OOP/AKN/Part_II/79
Example: Distance class
class Distance{
int feet;
float inches;
public:
Distance():feet(0),inches(0.0){}
Distance(int f, float i):feet(f),
inches(i){}
void showDistance(){
cout<<feet<<„‟‟<<inches<<„”‟<<endl;}
Distance addDistance(Distance);
};
OOP/AKN/Part_II/80
Example (contd.)
Distance Distance::addDistance(Distance d){
Distance res;
res.feet=feet+d.feet;
res.inches=inches+d.inches;
if(res.inches>=12.0){
res.inches-=12.0;
res.feet ++;
}
return res;
}
OOP/AKN/Part_II/81
Overloading + Operator
class Distance{
int feet;
float inches;
public:
Distance():feet(0),inches(0.0){}
Distance(int f, float i):feet(f),
inches(i){}
void showDistance();
Distance operator+(Distance);
};
OOP/AKN/Part_II/82
Example (contd.)
Distance Distance::operator+(Distance d){
int f=feet+d.feet;
float i=inches+d.inches;
if(i>=12.0){
i-=12.0;
f++;
}
return Distance(f,i);
}
OOP/AKN/Part_II/83
Example (contd.)
main(){
Distance d1(10,6), d2(11,7);
Distance d3=d1+d2;
d1.showDistance();
d2.showDistance();
d3.showDistance();
Distance d4=d1+d2+d3;
d4.showDistance();
}
10’ 6”
11’ 7”
22’ 1”
43’ 2”
OOP/AKN/Part_II/84
Task
Overlaod + and – operators for ComplexNum
class
Design the class
Define functions
Main function
OOP/AKN/Part_II/85
Passing two args: a non member function
class Distance{
int feet;
float inches;
public:
Distance();
Distance(int, float);
void showDistance();
};
Distance operator+(Distance, Distance);
OOP/AKN/Part_II/86
Example (contd.)
Distance operator+(Distance d1, Distance
d2){
int f = d1.feet+d2.feet;
float i = d1.inches+d2.inches;
if(i>=12.0){
i-=12.0;
f++;
}
return Distance(f,i);
}
Illegal
Accessing private
data members
OOP/AKN/Part_II/87
A solution: with a non member function
class Distance{
int feet;
float inches;
public:
Distance();
Distance(int, float);
void showDistance();
int getFeet(){return feet;}
float getInch(){return inch;}
};
Distance operator+(Distance, Distance);
OOP/AKN/Part_II/88
Passing Two Args
Distance operator+(Distance d1, Distance d2){
int f=d1.getFeet()+d2.getFeet();
float i=d1.getInch()+d2.getInch();
if(i>=12.0){
i-=12.0;
f++;
}
return Distance(f,i);
}
Note: In one program, there should be only one
operator overloading function for each operator.
Remember that this
function should be a
non-member!
OOP/AKN/Part_II/89
Friend Function
 A friend of a class is a function that is not a member of
the class but is permitted to use the private and
protected members of the class
 The name of the friend is not in the scope of the class
and the friend is not called with the member access
operator
 It can be declared in either private or public part of a
class
 A friend is explicitly declared inside the class
declaration of which it is a friend
 Key word is friend
OOP/AKN/Part_II/90
Friend Function
Example
class Sample{
int a;
int b;
public:
Sample(int x,int y):a(x),b(y){}
friend float mean(Sample s){
return float(s.a+s.b)/2.0;
}
};
OOP/AKN/Part_II/91
Example (contd.)
main(){
Sample test(13,10);
cout<<“mean is:”<<mean(test);
}
What is the use?
 If it is required to to operate on private
members of two different and unrelated
classes then friend to both classes will help.
 It can be helpful in operator overloading
OOP/AKN/Part_II/92
Overloading using friend function
class Distance{
int feet;
float inches;
public:
Distance();
Distance(int, float);
void showDistance();
friend Distance operator+(Distance,
Distance);
};
OOP/AKN/Part_II/93
Example (contd.)
Distance operator+(Distance d1, Distance
d1){
int f = d1.feet+d2.feet;
float i = d1.inches+d2.inches;
if(i>=12.0){
i-=12.0;
f++;
}
return Distance(f,i);
}
Legal
Accessing private data
members as it is a friend
function
OOP/AKN/Part_II/94
Example (contd.)
main(){
Distance d1(10,6), d2(11,5);
Distance d3=d1+d2;
d1.showDistance();
d2.showDistance();
d3.showDistance();
Distance d4=d1+d2+d3;
d4.showDistance();
}
OOP/AKN/Part_II/95
Example
 Matrix Vector product
class Matrix;
class Vector{
float v[4];
…
friend Vector operator* (Matrix &,Vector &);
};
class Matrix{
Vector m[4];
…
friend Vector operator*(Matrix&, Vector&);
};
OOP/AKN/Part_II/96
Example (Contd.)
Vector operator *(Matrix& mat, Vector& vec)
{
Vector res;
for(int i=0;i<4;i++){
res.v[i]=0;
for(int j=0;j<4;j++)
res.v[i]+=mat.m[i].v[j]*vec.v[i]; }
return res;
}
//Complete the program and execute
OOP/AKN/Part_II/97
Task
Overlaod + and – operators for ComplexNum
class using non-member(friend) functions.
Design the class
Define functions
Main function
OOP/AKN/Part_II/98
A Comparison
Access to
private part
Inside
scope of
the class
Invoked with
reference to
an object
Member
function
Yes Yes Yes
Static -
member
Yes Yes Optional
Friend
function
Yes No No
OOP/AKN/Part_II/99
Unary Operators
A Unary operator can be defined by either a
member function taking no arguments or a
non-member function taking one argument
Example
class X{
operator ++(); //prefix
operator ++(int); //postfix
}
OOP/AKN/Part_II/100
Example (contd.)
The int argument is simply a dummy
argument. It is used to distinguish between a
prefix and postfix application
Example
void operator ++(int){//postfix
feet++;
}
void operator ++(){//prefix
++feet;
}
d1++; d1.showDistance( );
++d2; d2.showDistance( );
OOP/AKN/Part_II/101
Mixed mode overloading
How to execute when two operands are of
different type?
Complex c,c1;
double d;
c+=c1; c+=d; c=d+c1; c=c1+d;
Complex operator +=(Complex a){
re+=a.re;
im+=a.im;
return *this;
}
Member
function
OOP/AKN/Part_II/102
Overloading(contd.)
Complex operator +=(double a){
re+=a;
return *this;
}
}; //end of class
Complex operator +(double a, Complex
b){
complex r=b;
return r+=a;
}
Non-Member
function
Member
function
OOP/AKN/Part_II/103
Overloading(contd.)
Complex operator +(Complex a,
double b){
complex r=a;
return r+=b;
}
Task
Complete the above program with all possible
types of operator overloading with mixed
mode arithmetic.
Non-Member
function
OOP/AKN/Part_II/104
Example
main(){
Complex c1, c2;
cin>>c1; cin >>c2;
Complex c3=c1+c2;
cout<<c1<<endl;
cout<<c2<<endl;
Complex c4=c1+c2+c3;
cout<<c4<<endl;
}
Error
OOP/AKN/Part_II/105
Overloading Stream Insertion and extraction
operators
class Complex{
…
friend ostream& operator<<(ostream&,
Complex);
friend istream& operator>>(istream&,
Complex&);
};
ostream& operator<<(ostream& out,
Complex c){
out<<c.re<<“ + i”<<c.img<<endl;
return out;}
OOP/AKN/Part_II/106
Operator overloading
istream& operator>>(istream& in,
Complex &c){
in>>c.re>>c.img;
return in;
}
 These functions must be non members as
the objects of class Complex appears in
each case as the right operand and the
function can not be a part of class ostream
and istream
OOP/AKN/Part_II/107
Data Conversion
 „=„ is a special operator with complex properties.
 When both sides are of equal type, the compiler
does not need any special instructions to operate.
 If they are different ?
Conversion between Basic Types:
(int)=(float); //allowed
 Each such conversion has its own routine, built
into the compiler. This is called an implicit
conversion(casting).
OOP/AKN/Part_II/108
Data Conversion (contd.)
 Sometimes we need explicit casting like
float ..= float(int ..)
 This conversion also use the built-in routines
available with the compiler.
 User Defined to Basic Types
float ..=float(Distance);
float f = d1;
Operator float(){
float ft=inches/12;
ft+=float(feet);
return ft;}
OOP/AKN/Part_II/109
Data Conversion(contd.)
 Basic to User-defined type
Distance d1=2.35;
Distance(float f){
feet=int(f);
inches=12*(f-feet);
}
 User-defined to User-defined type
objA=objB;//both are objects of
different classes
OOP/AKN/Part_II/110
Data Conversion(contd.)
class Rect{
double xco;
double yco;
public:
…
}
class Polar{
double radius;
double angle;
public:
…
OOP/AKN/Part_II/111
Data Conversion(contd.)
operator Rect(){
double x=radius*cos(angle);
double y=radius*sin(angle);
return Rect(x,y);
} //inside class declaration
}; //class ends here
main(){
Rect rec; Polar pol(10.0,0.785398);
rec=pol;
pol.display(); rec.display();}
OOP/AKN/Part_II/112
Pitfalls/Guidelines of Data Conversion
Use Similar meanings
Use overload operators to perform similar
operations as in basic types
Use Similar Syntax
Don‟t try to create new operators also don‟t design
binary operators for unary action and vice versa
Show Restraint
Don‟t overload operators if not required frequently.
Also Limit the overloaded operators for a class to
manage complexity
OOP/AKN/Part_II/113
Pitfalls/Guidelines of Data Conversion
Avoid Ambiguity
Don‟t try to overload the same operator in many
different ways in a same program. This may be a
confusion for the compiler.
Not All operators can be overloaded.
*(pointer), .(access op), :: (scope),
?: (ternary), and sizeof()
OOP/AKN/Part_II/114
Copying Objects
class Table{
char *name;
float size;
public:
Table(float s=15){
name=new char[size=s];}
};
1.Table t1;
2.Table t2=t1;
3.Table t3;
4.t3=t2;
5.Table t4(t3);
Default Constructor
//constructor is called
//copy initialization
//constructor is called
//copy assignment
//copy constructor
OOP/AKN/Part_II/115
Copying Objects (contd.)
 Line 1: default constructor is called and the
address for the memory allocated is stored in
name variable.
 Line 2: It is initialized by copying. i.e memberwise
copying t2.name=t1.name;
 Now both object point to same memory area.
 Line 3: default constructor is called and the
address for the memory allocated is stored in
name variable.(t3.name)
 Line 4: t3.name is overwritten by t2.name which is
nothing but t1.name
 Line 5: . . .
OOP/AKN/Part_II/116
Copying Objects (contd.)
Conclusion:
1. Storage for t3 is lost to program for ever
2. All objects point to same memory area
3. Destructor will be called Four times(?)
i.e. the same memory area will be deleted four
times and the result is undefined( may be
disastrous!)
Also called as shallow copy
OOP/AKN/Part_II/117
Copy Constructors
Make a duplicate copy of an object of the
same class, the default make a
memberwise copy of the the object
The default Copy constructors is created by
the compiler automatically.
A local copy of the object is constructed
which may create anomalies.
Copy constructors can also be defined by
us, which can be designed meaning fully
according to the requirement.
OOP/AKN/Part_II/118
Copy Constructors(Deep Copy)
class Table{
. . .
Table (const Table&);
Table& operator=(const Table&);
};
Table::Table(const Table& t){
name=new char[size=t.size];
strcpy(name,t.name);
}
Copy constructor
Copy assignment
OOP/AKN/Part_II/119
Copy Constructors(contd.)
Table& operator=(const Table& t){
if(this!=&t){
delete name;
name=new char[size=t.size];
strcpy(name,t.name);
}
return *this;
}
 Why copy constructor takes the argument as const and
a reference?
OOP/AKN/Part_II/120
The “This” Pointer
Every object has access to its own address
through a pointer called „this‟
The this pointer is passed as an implicit first
argument on every non-static member
function call for an object.
The this pointer is implicitly used to refer both
the data and function members of an object
It can also be used explicitly;
Example: (*this).x=5; or this->x=5;
OOP/AKN/Part_II/121
Friend Classes
 If a class is declared as friend to another class then
it is allowed to access all the members of that class
 To declare class A as a friend of class B, place the
corresponding declaration in the definition of class
B.
Example:
class ClassOne{
...
friend ClassTwo;
};
 Friendship is neither symmetric nor transitive.
ClassTwo is allowed to
access all the members of
ClassOne
OOP/AKN/Part_II/122
Nested Classes
Classes like blocks and namespaces can be
nested.
These are all scopes and nesting allows local
hiding of names and local allocation of
resources.
This is often the case when a class is
needed as part of the implementation of a
larger construct
OOP/AKN/Part_II/123
Nested Classes (Contd.)
char c; //::c
class X{
char c; //X::c
public:
class Y{
char c; //X::Y::c
public:
void foo(char e){
X t; ::c=t.X::c=c=e;}
};
};
OOP/AKN/Part_II/124
Local / Global classes
 Class declared out of all scopes are called
global class.
These classes may be used to create
objects anywhere in the program.
Class declared inside a scope (function etc)
are called local class.
Objects of this class can be used inside the
specified scope only.
OOP/AKN/Part_II/125
A more complete example
class String{
int length;
char *ptr;
void setString(const char*);
public:
String(const char* = ““);
String(const String&);
~String();
String& operator=(const String&);
String& operator +=(const String &);
bool operator !()const;
bool operator ==(String&)const;
OOP/AKN/Part_II/126
Example (contd.)
bool operator <(String)const;
bool operator !=(String&)const;
bool operator >(String&)const;
bool operator <=(String&)const;
bool operator >=(String&)const;
char& operator[](int);
String operator()(int,int);
int getLength()const;
friend ostream& operator<<(ostream&, const
String&);
friend istream& operator>>(istream&,
String&);
}; //end of class def.
OOP/AKN/Part_II/127
Example (contd.)
void String::setString(const char *s2){
ptr=new char[length+1];
strcpy(ptr,s2);}
String::String(const char* s){
length=strlen(s);
setString(s);}
String::String(String& copy){
length=copy.length;
setString(copy.ptr);}
String::~String(){delete []ptr;}
OOP/AKN/Part_II/128
Example (contd.)
String& String::operator=(String& right){
if(&right!=this){
delete [] ptr; length=right.length;
setString(right.ptr);
}
return *this;
}
String& String::operator+=(String& right){
char *tmp=ptr; length+=right.length;
ptr=new char[length+1]; strcpy(ptr,tmp);
strcat(ptr,right.ptr); delete [] tmp;
return *this;
}
OOP/AKN/Part_II/129
Example (contd.)
bool String::operator!()const{
return length==0;}
bool String::operator==(String&
right)const{
return strcmp(ptr,right.ptr)==0;}
bool String::operator<(String
right)const{
return strcmp(ptr,right.ptr)<0;}
bool String::operator!=(String&
right)const{
return !(*this==right);}
OOP/AKN/Part_II/130
Example (contd.)
bool String::operator>(const String&
right)const{
return right<*this; }
bool String::operator<=(const String&
right)const{
return !(right<*this); }
bool String::operator>=(const String&
right)const{
return !(*this<right); }
OOP/AKN/Part_II/131
Example (contd.)
char& String::operator[](int sbsrpt){
if(sbsrpt>=0 && sbsrpt<length)
return ptr[sbsrpt]; }
String String::operator()(int i,int l){
if(i>=0 && i<length && l>=0 )
int len;
if((l==0)||(i+l>length))
len=length-i;
else
len=l;
char* tmp=new char[len+1];
strncpy(tmp,&ptr[i],len); tmp[len]=„0‟;
String tmpString(tmp); delete[]tmp;
return tmpString;}
OOP/AKN/Part_II/132
Example (contd.)
int String::getLength()const{
return length; }
ostream& operator<<(ostream& out,
const String& s){
out<<s.ptr; return out; }
istream& operator>>(istream& in,
String& s){
char tmp[500];
in>>tmp; s=tmp; return in;}
OOP/AKN/Part_II/133
Example (contd.)
#include<iostream>
#include<cstring>
main(){
String s1(“Happy”), s2(“birthday”),s;
cout<<(s2==s1?”true”:”false”)<<endl;
cout<<(s2!=s1?”true”:”false”)<<endl;
cout<<(s2>s1?”true”:”false”)<<endl;
cout<<(s2>=s1?”true”:”false”)<<endl;
cout<<(s2<=s1?”true”:”false”)<<endl;
if(!s){cout<<“empty”; s=s1;cout<<s;}
OOP/AKN/Part_II/134
Example (contd.)
s1+=s2;
cout<<s1 <<endl;
s1+=“ to you”;
cout<<s1<<endl;
cout<<s1(0,14)<<endl;
String *s4ptr=new String(s1);
cout<<*s4ptr;
S1[0]=„H‟;s1[6]=„B‟;
cout<<s1;
}
OOP/AKN/Part_II/135
Task
 Design a class called LargeInt to handle integers
of large size (O(103 ) digits)
 overload all arithmetic operators (+, -, *, /, %)
 overload all unary (++, --, +=, . . .) operators
 overload all relational operators
 design copy constructor and copy assignment
 Member function to test primality
 Write a suitable main function to demonstrate all
above facilities
OOP/AKN/Part_II/136
Readings
Programming
 Bjarne Stroustrup, The C++ Programming Language, PE
 Lippman, Lajoie, C++ Primer, Addison-Wesley
 B. Eckel, Thinking in C++, Vol I and Vol II
 Deitel & Deitel, C++ How to program
 Schildt, C++ The complete reference
 S. Sahay, OOP with C++
 E. Balagurusami, Object oriented programming with C++
Concepts
 G.Booch, Object Oriented Analysis & Design
 Bertand Meyer, Object Oriented Software Construction

More Related Content

What's hot

Std 12 computer chapter 6 object oriented concepts (part 1)
Std 12 computer chapter 6 object oriented concepts (part 1)Std 12 computer chapter 6 object oriented concepts (part 1)
Std 12 computer chapter 6 object oriented concepts (part 1)Nuzhat Memon
 
Object-Oriented Concepts
Object-Oriented ConceptsObject-Oriented Concepts
Object-Oriented ConceptsAbdalla Mahmoud
 
Oops and c fundamentals
Oops and c fundamentals Oops and c fundamentals
Oops and c fundamentals umesh patil
 
Object Oriented Programming Lecture Notes
Object Oriented Programming Lecture NotesObject Oriented Programming Lecture Notes
Object Oriented Programming Lecture NotesFellowBuddy.com
 
OOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and ObjectOOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and Objectdkpawar
 
Concepts In Object Oriented Programming Languages
Concepts In Object Oriented Programming LanguagesConcepts In Object Oriented Programming Languages
Concepts In Object Oriented Programming Languagesppd1961
 
SKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPTSKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPTSkillwise Group
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops conceptsNilesh Dalvi
 
Object Oriented Programming In .Net
Object Oriented Programming In .NetObject Oriented Programming In .Net
Object Oriented Programming In .NetGreg Sohl
 
Object Oriented Concepts in Real Projects
Object Oriented Concepts in Real ProjectsObject Oriented Concepts in Real Projects
Object Oriented Concepts in Real ProjectsEPAM
 
Java oops and fundamentals
Java oops and fundamentalsJava oops and fundamentals
Java oops and fundamentalsjavaease
 
Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1 Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1 Sakthi Durai
 
Advanced OOP - Laws, Principles, Idioms
Advanced OOP - Laws, Principles, IdiomsAdvanced OOP - Laws, Principles, Idioms
Advanced OOP - Laws, Principles, IdiomsClint Edmonson
 
the Concept of Object-Oriented Programming
the Concept of Object-Oriented Programmingthe Concept of Object-Oriented Programming
the Concept of Object-Oriented ProgrammingAida Ramlan II
 
OBJECT ORIENTED ROGRAMMING With Question And Answer Full
OBJECT ORIENTED ROGRAMMING With Question And Answer  FullOBJECT ORIENTED ROGRAMMING With Question And Answer  Full
OBJECT ORIENTED ROGRAMMING With Question And Answer FullManas Rai
 

What's hot (20)

Std 12 computer chapter 6 object oriented concepts (part 1)
Std 12 computer chapter 6 object oriented concepts (part 1)Std 12 computer chapter 6 object oriented concepts (part 1)
Std 12 computer chapter 6 object oriented concepts (part 1)
 
Object-Oriented Concepts
Object-Oriented ConceptsObject-Oriented Concepts
Object-Oriented Concepts
 
Oops and c fundamentals
Oops and c fundamentals Oops and c fundamentals
Oops and c fundamentals
 
Object Oriented Programming Lecture Notes
Object Oriented Programming Lecture NotesObject Oriented Programming Lecture Notes
Object Oriented Programming Lecture Notes
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
OOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and ObjectOOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and Object
 
Concepts In Object Oriented Programming Languages
Concepts In Object Oriented Programming LanguagesConcepts In Object Oriented Programming Languages
Concepts In Object Oriented Programming Languages
 
SKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPTSKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPT
 
Oop Presentation
Oop PresentationOop Presentation
Oop Presentation
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops concepts
 
Object Oriented Programming In .Net
Object Oriented Programming In .NetObject Oriented Programming In .Net
Object Oriented Programming In .Net
 
Unit 1 OOSE
Unit 1 OOSE Unit 1 OOSE
Unit 1 OOSE
 
Object Oriented Concepts in Real Projects
Object Oriented Concepts in Real ProjectsObject Oriented Concepts in Real Projects
Object Oriented Concepts in Real Projects
 
Java oops and fundamentals
Java oops and fundamentalsJava oops and fundamentals
Java oops and fundamentals
 
Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1 Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1
 
Advanced OOP - Laws, Principles, Idioms
Advanced OOP - Laws, Principles, IdiomsAdvanced OOP - Laws, Principles, Idioms
Advanced OOP - Laws, Principles, Idioms
 
the Concept of Object-Oriented Programming
the Concept of Object-Oriented Programmingthe Concept of Object-Oriented Programming
the Concept of Object-Oriented Programming
 
2 Object Oriented Programming
2 Object Oriented Programming2 Object Oriented Programming
2 Object Oriented Programming
 
OBJECT ORIENTED ROGRAMMING With Question And Answer Full
OBJECT ORIENTED ROGRAMMING With Question And Answer  FullOBJECT ORIENTED ROGRAMMING With Question And Answer  Full
OBJECT ORIENTED ROGRAMMING With Question And Answer Full
 
Object-oriented concepts
Object-oriented conceptsObject-oriented concepts
Object-oriented concepts
 

Viewers also liked

Software Engineering an Introduction
Software Engineering an IntroductionSoftware Engineering an Introduction
Software Engineering an IntroductionAjit Nayak
 
NS2: AWK and GNUplot - PArt III
NS2: AWK and GNUplot - PArt IIINS2: AWK and GNUplot - PArt III
NS2: AWK and GNUplot - PArt IIIAjit Nayak
 
Is your company fully engaged towards innovation?
Is your company fully engaged towards innovation?Is your company fully engaged towards innovation?
Is your company fully engaged towards innovation?Sebastien Juras
 
Omg Fundamental Certification 4
Omg Fundamental Certification 4Omg Fundamental Certification 4
Omg Fundamental Certification 4Ricardo Quintero
 
Introduction to database-Formal Query language and Relational calculus
Introduction to database-Formal Query language and Relational calculusIntroduction to database-Formal Query language and Relational calculus
Introduction to database-Formal Query language and Relational calculusAjit Nayak
 
Computer Networks Module III
Computer Networks Module IIIComputer Networks Module III
Computer Networks Module IIIAjit Nayak
 
Psychology explains the power of Storytelling
Psychology explains the power of StorytellingPsychology explains the power of Storytelling
Psychology explains the power of StorytellingSebastien Juras
 
Introduction to database-Transaction Concurrency and Recovery
Introduction to database-Transaction Concurrency and RecoveryIntroduction to database-Transaction Concurrency and Recovery
Introduction to database-Transaction Concurrency and RecoveryAjit Nayak
 
Software Engineering :UML class diagrams
Software Engineering :UML class diagramsSoftware Engineering :UML class diagrams
Software Engineering :UML class diagramsAjit Nayak
 
Uml Omg Fundamental Certification 1
Uml Omg Fundamental Certification 1Uml Omg Fundamental Certification 1
Uml Omg Fundamental Certification 1Ricardo Quintero
 
Database Programming using SQL
Database Programming using SQLDatabase Programming using SQL
Database Programming using SQLAjit Nayak
 
Uml Omg Fundamental Certification 3
Uml Omg Fundamental Certification 3Uml Omg Fundamental Certification 3
Uml Omg Fundamental Certification 3Ricardo Quintero
 
Parallel programming using MPI
Parallel programming using MPIParallel programming using MPI
Parallel programming using MPIAjit Nayak
 
INNOVATION IS NOT AN OPTION
INNOVATION IS NOT AN OPTIONINNOVATION IS NOT AN OPTION
INNOVATION IS NOT AN OPTIONSebastien Juras
 
Six things to know about your brain to become an expert
Six things to know about your brain to become an expertSix things to know about your brain to become an expert
Six things to know about your brain to become an expertSebastien Juras
 
Innovation is almost impossible for older companies
Innovation is almost impossible for older companiesInnovation is almost impossible for older companies
Innovation is almost impossible for older companiesSebastien Juras
 
03 administracion de requisitos
03 administracion de requisitos03 administracion de requisitos
03 administracion de requisitosRicardo Quintero
 

Viewers also liked (20)

Software Engineering an Introduction
Software Engineering an IntroductionSoftware Engineering an Introduction
Software Engineering an Introduction
 
NS2: AWK and GNUplot - PArt III
NS2: AWK and GNUplot - PArt IIINS2: AWK and GNUplot - PArt III
NS2: AWK and GNUplot - PArt III
 
Is your company fully engaged towards innovation?
Is your company fully engaged towards innovation?Is your company fully engaged towards innovation?
Is your company fully engaged towards innovation?
 
Omg Fundamental Certification 4
Omg Fundamental Certification 4Omg Fundamental Certification 4
Omg Fundamental Certification 4
 
Introduction to database-Formal Query language and Relational calculus
Introduction to database-Formal Query language and Relational calculusIntroduction to database-Formal Query language and Relational calculus
Introduction to database-Formal Query language and Relational calculus
 
Computer Networks Module III
Computer Networks Module IIIComputer Networks Module III
Computer Networks Module III
 
Psychology explains the power of Storytelling
Psychology explains the power of StorytellingPsychology explains the power of Storytelling
Psychology explains the power of Storytelling
 
Introduction to database-Transaction Concurrency and Recovery
Introduction to database-Transaction Concurrency and RecoveryIntroduction to database-Transaction Concurrency and Recovery
Introduction to database-Transaction Concurrency and Recovery
 
Manual 02
Manual 02Manual 02
Manual 02
 
Software Engineering :UML class diagrams
Software Engineering :UML class diagramsSoftware Engineering :UML class diagrams
Software Engineering :UML class diagrams
 
01 conceptos de diseño
01 conceptos de diseño01 conceptos de diseño
01 conceptos de diseño
 
Uml Omg Fundamental Certification 1
Uml Omg Fundamental Certification 1Uml Omg Fundamental Certification 1
Uml Omg Fundamental Certification 1
 
Database Programming using SQL
Database Programming using SQLDatabase Programming using SQL
Database Programming using SQL
 
Uml Omg Fundamental Certification 3
Uml Omg Fundamental Certification 3Uml Omg Fundamental Certification 3
Uml Omg Fundamental Certification 3
 
Perfiles UML
Perfiles UMLPerfiles UML
Perfiles UML
 
Parallel programming using MPI
Parallel programming using MPIParallel programming using MPI
Parallel programming using MPI
 
INNOVATION IS NOT AN OPTION
INNOVATION IS NOT AN OPTIONINNOVATION IS NOT AN OPTION
INNOVATION IS NOT AN OPTION
 
Six things to know about your brain to become an expert
Six things to know about your brain to become an expertSix things to know about your brain to become an expert
Six things to know about your brain to become an expert
 
Innovation is almost impossible for older companies
Innovation is almost impossible for older companiesInnovation is almost impossible for older companies
Innovation is almost impossible for older companies
 
03 administracion de requisitos
03 administracion de requisitos03 administracion de requisitos
03 administracion de requisitos
 

Similar to Object Oriented Programming using C++ Part II

Lecture 2 cst 205-281 oop
Lecture 2   cst 205-281 oopLecture 2   cst 205-281 oop
Lecture 2 cst 205-281 oopktuonlinenotes
 
Chapter 6 OOPS Concept
Chapter 6 OOPS ConceptChapter 6 OOPS Concept
Chapter 6 OOPS ConceptAmrit Kaur
 
Chapter 1- Introduction.ppt
Chapter 1- Introduction.pptChapter 1- Introduction.ppt
Chapter 1- Introduction.pptTigistTilahun1
 
1Intro.PPT
1Intro.PPT1Intro.PPT
1Intro.PPTMitrBhat
 
Abstraction file
Abstraction fileAbstraction file
Abstraction fileJames Wong
 
Abstraction file
Abstraction fileAbstraction file
Abstraction fileFraboni Ec
 
Abstraction file
Abstraction fileAbstraction file
Abstraction fileTony Nguyen
 
CPP_,module2_1.pptx
CPP_,module2_1.pptxCPP_,module2_1.pptx
CPP_,module2_1.pptxAbhilashTom4
 
Programming Laboratory Unit 1.pdf
Programming Laboratory Unit 1.pdfProgramming Laboratory Unit 1.pdf
Programming Laboratory Unit 1.pdfswapnilslide2019
 
Java Progamming Paradigms, OOPS Concept, Introduction to Java, Structure of J...
Java Progamming Paradigms, OOPS Concept, Introduction to Java, Structure of J...Java Progamming Paradigms, OOPS Concept, Introduction to Java, Structure of J...
Java Progamming Paradigms, OOPS Concept, Introduction to Java, Structure of J...Sakthi Durai
 
CSCI 383 Lecture 3 and 4: Abstraction
CSCI 383 Lecture 3 and 4: AbstractionCSCI 383 Lecture 3 and 4: Abstraction
CSCI 383 Lecture 3 and 4: AbstractionJI Ruan
 
M.c.a. (sem iv)- java programming
M.c.a. (sem   iv)- java programmingM.c.a. (sem   iv)- java programming
M.c.a. (sem iv)- java programmingPraveen Chowdary
 
1 intro
1 intro1 intro
1 introabha48
 

Similar to Object Oriented Programming using C++ Part II (20)

Lecture 2 cst 205-281 oop
Lecture 2   cst 205-281 oopLecture 2   cst 205-281 oop
Lecture 2 cst 205-281 oop
 
Mca 504 dotnet_unit3
Mca 504 dotnet_unit3Mca 504 dotnet_unit3
Mca 504 dotnet_unit3
 
Chapter 6 OOPS Concept
Chapter 6 OOPS ConceptChapter 6 OOPS Concept
Chapter 6 OOPS Concept
 
Chapter 1- Introduction.ppt
Chapter 1- Introduction.pptChapter 1- Introduction.ppt
Chapter 1- Introduction.ppt
 
1Intro.PPT
1Intro.PPT1Intro.PPT
1Intro.PPT
 
MCA NOTES.pdf
MCA NOTES.pdfMCA NOTES.pdf
MCA NOTES.pdf
 
TEST PPT
TEST PPTTEST PPT
TEST PPT
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
 
CPP_,module2_1.pptx
CPP_,module2_1.pptxCPP_,module2_1.pptx
CPP_,module2_1.pptx
 
Programming Laboratory Unit 1.pdf
Programming Laboratory Unit 1.pdfProgramming Laboratory Unit 1.pdf
Programming Laboratory Unit 1.pdf
 
Java Progamming Paradigms, OOPS Concept, Introduction to Java, Structure of J...
Java Progamming Paradigms, OOPS Concept, Introduction to Java, Structure of J...Java Progamming Paradigms, OOPS Concept, Introduction to Java, Structure of J...
Java Progamming Paradigms, OOPS Concept, Introduction to Java, Structure of J...
 
CSCI 383 Lecture 3 and 4: Abstraction
CSCI 383 Lecture 3 and 4: AbstractionCSCI 383 Lecture 3 and 4: Abstraction
CSCI 383 Lecture 3 and 4: Abstraction
 
M.c.a. (sem iv)- java programming
M.c.a. (sem   iv)- java programmingM.c.a. (sem   iv)- java programming
M.c.a. (sem iv)- java programming
 
1 intro
1 intro1 intro
1 intro
 

More from Ajit Nayak

Software Engineering : Software testing
Software Engineering : Software testingSoftware Engineering : Software testing
Software Engineering : Software testingAjit Nayak
 
Software Engineering :Behavioral Modelling - II State diagram
Software Engineering :Behavioral Modelling - II State diagramSoftware Engineering :Behavioral Modelling - II State diagram
Software Engineering :Behavioral Modelling - II State diagramAjit Nayak
 
Software Engineering :Behavioral Modelling - I Sequence diagram
Software Engineering :Behavioral Modelling - I Sequence diagram Software Engineering :Behavioral Modelling - I Sequence diagram
Software Engineering :Behavioral Modelling - I Sequence diagram Ajit Nayak
 
Software Engineering : OOAD using UML
Software Engineering : OOAD using UMLSoftware Engineering : OOAD using UML
Software Engineering : OOAD using UMLAjit Nayak
 
Software Engineering : Requirement Analysis & Specification
Software Engineering : Requirement Analysis & SpecificationSoftware Engineering : Requirement Analysis & Specification
Software Engineering : Requirement Analysis & SpecificationAjit Nayak
 
Software Engineering : Process Models
Software Engineering : Process ModelsSoftware Engineering : Process Models
Software Engineering : Process ModelsAjit Nayak
 
Ns2: Introduction - Part I
Ns2: Introduction - Part INs2: Introduction - Part I
Ns2: Introduction - Part IAjit Nayak
 
Ns2: OTCL - PArt II
Ns2: OTCL - PArt IINs2: OTCL - PArt II
Ns2: OTCL - PArt IIAjit Nayak
 
Socket programming using C
Socket programming using CSocket programming using C
Socket programming using CAjit Nayak
 
Object Oriented Analysis Design using UML
Object Oriented Analysis Design using UMLObject Oriented Analysis Design using UML
Object Oriented Analysis Design using UMLAjit Nayak
 
Operating Systems Part III-Memory Management
Operating Systems Part III-Memory ManagementOperating Systems Part III-Memory Management
Operating Systems Part III-Memory ManagementAjit Nayak
 
Operating Systems Part I-Basics
Operating Systems Part I-BasicsOperating Systems Part I-Basics
Operating Systems Part I-BasicsAjit Nayak
 
Operating Systems Part II-Process Scheduling, Synchronisation & Deadlock
Operating Systems Part II-Process Scheduling, Synchronisation & DeadlockOperating Systems Part II-Process Scheduling, Synchronisation & Deadlock
Operating Systems Part II-Process Scheduling, Synchronisation & DeadlockAjit Nayak
 
Introduction to database-Normalisation
Introduction to database-NormalisationIntroduction to database-Normalisation
Introduction to database-NormalisationAjit Nayak
 
Introduction to database-ER Model
Introduction to database-ER ModelIntroduction to database-ER Model
Introduction to database-ER ModelAjit Nayak
 
Computer Networks Module II
Computer Networks Module IIComputer Networks Module II
Computer Networks Module IIAjit Nayak
 
Computer Networks Module I
Computer Networks Module IComputer Networks Module I
Computer Networks Module IAjit Nayak
 
Object Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part IIIObject Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part IIIAjit Nayak
 
Object Oriented Programming using C++ Part I
Object Oriented Programming using C++ Part IObject Oriented Programming using C++ Part I
Object Oriented Programming using C++ Part IAjit Nayak
 
Computer Fundamentals & Intro to C Programming module i
Computer Fundamentals & Intro to C Programming module iComputer Fundamentals & Intro to C Programming module i
Computer Fundamentals & Intro to C Programming module iAjit Nayak
 

More from Ajit Nayak (20)

Software Engineering : Software testing
Software Engineering : Software testingSoftware Engineering : Software testing
Software Engineering : Software testing
 
Software Engineering :Behavioral Modelling - II State diagram
Software Engineering :Behavioral Modelling - II State diagramSoftware Engineering :Behavioral Modelling - II State diagram
Software Engineering :Behavioral Modelling - II State diagram
 
Software Engineering :Behavioral Modelling - I Sequence diagram
Software Engineering :Behavioral Modelling - I Sequence diagram Software Engineering :Behavioral Modelling - I Sequence diagram
Software Engineering :Behavioral Modelling - I Sequence diagram
 
Software Engineering : OOAD using UML
Software Engineering : OOAD using UMLSoftware Engineering : OOAD using UML
Software Engineering : OOAD using UML
 
Software Engineering : Requirement Analysis & Specification
Software Engineering : Requirement Analysis & SpecificationSoftware Engineering : Requirement Analysis & Specification
Software Engineering : Requirement Analysis & Specification
 
Software Engineering : Process Models
Software Engineering : Process ModelsSoftware Engineering : Process Models
Software Engineering : Process Models
 
Ns2: Introduction - Part I
Ns2: Introduction - Part INs2: Introduction - Part I
Ns2: Introduction - Part I
 
Ns2: OTCL - PArt II
Ns2: OTCL - PArt IINs2: OTCL - PArt II
Ns2: OTCL - PArt II
 
Socket programming using C
Socket programming using CSocket programming using C
Socket programming using C
 
Object Oriented Analysis Design using UML
Object Oriented Analysis Design using UMLObject Oriented Analysis Design using UML
Object Oriented Analysis Design using UML
 
Operating Systems Part III-Memory Management
Operating Systems Part III-Memory ManagementOperating Systems Part III-Memory Management
Operating Systems Part III-Memory Management
 
Operating Systems Part I-Basics
Operating Systems Part I-BasicsOperating Systems Part I-Basics
Operating Systems Part I-Basics
 
Operating Systems Part II-Process Scheduling, Synchronisation & Deadlock
Operating Systems Part II-Process Scheduling, Synchronisation & DeadlockOperating Systems Part II-Process Scheduling, Synchronisation & Deadlock
Operating Systems Part II-Process Scheduling, Synchronisation & Deadlock
 
Introduction to database-Normalisation
Introduction to database-NormalisationIntroduction to database-Normalisation
Introduction to database-Normalisation
 
Introduction to database-ER Model
Introduction to database-ER ModelIntroduction to database-ER Model
Introduction to database-ER Model
 
Computer Networks Module II
Computer Networks Module IIComputer Networks Module II
Computer Networks Module II
 
Computer Networks Module I
Computer Networks Module IComputer Networks Module I
Computer Networks Module I
 
Object Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part IIIObject Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part III
 
Object Oriented Programming using C++ Part I
Object Oriented Programming using C++ Part IObject Oriented Programming using C++ Part I
Object Oriented Programming using C++ Part I
 
Computer Fundamentals & Intro to C Programming module i
Computer Fundamentals & Intro to C Programming module iComputer Fundamentals & Intro to C Programming module i
Computer Fundamentals & Intro to C Programming module i
 

Recently uploaded

(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college projectTonystark477637
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 

Recently uploaded (20)

(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 

Object Oriented Programming using C++ Part II

  • 1. OOP/AKN/Part_II/1 Object Oriented Programming Concepts Part II Ajit K Nayak, Ph.D. SOA University
  • 2. OOP/AKN/Part_II/2 Contents  Object Oriented Concepts  Class & Objects  Constructor & Destrctors  Operator Overloading  Friend function  Data Conversion  This pointer  Friend class  Nested Class
  • 3. OOP/AKN/Part_II/3 How to Solve a Complex System?  The Technique of mastering complexity has been known since ancient times “Divide and Rule” …Dijkstra i.e Decomposition of the Problem  Intelligent decomposition directly addresses the inherent complexity of software by forcing a division of systems state space …Parnas
  • 4. OOP/AKN/Part_II/4 Decomposition  Algorithmic/Functional Decomposition 1. Divide the system to some modules 2. Each module should denote a major step in overall process.  Object Oriented Decomposition 1. View the world as a set of autonomous agents that collaborate to perform some higher level behaviour.
  • 5. OOP/AKN/Part_II/5 Functional Decomposition The System Function1 Function2 Function3 Function11 Function12 . . . . . . . . . . . . . . . . . .
  • 7. OOP/AKN/Part_II/7 Functional decomposition Main Problem: No. of words in a file getWordFromFile addToWordList getWordList sortword checkWord Sorted Words Word List Flag Words Words(prev,curr) WordWord Words getSortedWordList countDiffWords printResult Sorted Words Sorted Words Count Count
  • 8. OOP/AKN/Part_II/8 OO Decomposition Problem: No. of words in a file File WordList getWord Autonomous Agents(Objects)
  • 9. OOP/AKN/Part_II/9 Which is the Right way?  Algorithmic view highlights the ordering of events  Object Oriented view emphasizes the agents (objects) that either cause action or to be acted upon  Both The Philosophy are important  If the system is Very large, Complex, to be Extended, Maintained then choose OO approach.
  • 10. OOP/AKN/Part_II/10 Procedural Programming  With procedural programming, you are able to combine sequences of calling statements into one single place.  A procedure call is used to invoke the procedure. After the sequence is processed, flow of control proceeds right after the position where the call was made . Main Program Procedure
  • 11. OOP/AKN/Part_II/11  Now a program can be viewed as a sequence of procedure calls.  The main program is responsible to pass data to the individual calls, the data is processed by the procedures and the resulting data is presented.  Thus, the flow of data can be illustrated as a hierarchical graph, a tree. Procedural Programming
  • 12. OOP/AKN/Part_II/12 Procedure Program view Main Program Data Procedure1 Procedure2 Procedure3 Procedural Programming uses Algorithms as the Basic building block.
  • 13. OOP/AKN/Part_II/13 Features of Object Oriented Programming  Abstraction Encapsulation  Composition  Aggregation  Association  Inheritance  Polymorphism  Dynamic Binding
  • 14. OOP/AKN/Part_II/14 Abstraction  An Abstraction denotes the Essential characteristics of an object that distinguishes it from all other kinds of objects and thus defines sharply defined conceptual boundaries, relative to the perspective of the viewer. …Grady Booch
  • 16. OOP/AKN/Part_II/16 Abstraction(contd.)  It focuses on the outside view(interface) of an object. Therefore, it serves to separate an objects essential behaviour from its implementation.  It is used to reduce complexity by ignoring some aspect of a subject that are not relevant to the current purpose. Example : A MAP (is not an exact picture)  Only the essential features of an area are shown  Unimportant features are ignored.
  • 17. OOP/AKN/Part_II/17 Abstraction(contd.)  All Abstractions have static as well as dynamic properties. Example: A FILE Static : Name, Size, Content Dynamic: the value contained in static properties.  It is dynamic because a file may grow or shrink in size  Its name and content may change
  • 19. OOP/AKN/Part_II/19 Encapsulation(contd.)  It is the process of compartmentalising the elements of an abstraction that constitute its structure and behaviour. …Grady Booch • In this process we keep the properties (or structure or states) and behaviour of an object in one place bundeled together. • It supports information hiding i.e. hiding all the information that is unnecessary to the outside world.
  • 20. OOP/AKN/Part_II/20 Encapsulation  Encapsulation helps to achieve abstraction by hiding the implementation of behaviours  It provides explicit barriers among different abstractions Example: Riding a Bike • Most of the riders are ignorant about the detail structure of an IC Engine. • Changing gears on your bike need not require to know “how the gear mechanism works” just need to know which lever to move.
  • 21. OOP/AKN/Part_II/21  Composition defines a has-a relationship  An organized collection of components interacting to achieve a coherent, common behavior  The automobile has a windshield.  It deals with a single, complex system as an organization of more numerous but simpler systems Composition
  • 22. OOP/AKN/Part_II/22 Composition (examples) A human being consists of a respiratory system, a circulatory system, an immune system, a nervous systems, a skeletal system, etc An aircraft consists of a propulsion system, a control system, a navigation system, etc An operating system consists of a user interface, a file system, a network system, a memory management system, etc
  • 24. OOP/AKN/Part_II/24 Plant is a part of Garden(whole) (Association) Flower is a part of Plant(whole) (Aggregation) • Garden permits different plants to be raised over time. • Replacing a plant does not change the identity of a garden. • Removing a Garden does not necessarily destroy all of its plants i.e. the life time of Plant(part) and Garden (whole) are independent. Example
  • 25. OOP/AKN/Part_II/25  Inheritance is the most important is-a kind of hierarchy Inheritance helps to share the structure and behaviour defined in one or more classes …Grady Booch i.e a sub-class inherits from one or more super-classes and subclass is dependent upon superclass Inheritance
  • 27. OOP/AKN/Part_II/27 Examples (Inheritance)  Mammal is a kind of Animal  Tiger is a kind of Mammal  Cheetah is a kind of Tiger  House is a kind of Tangible Asset  Quick sort is a kind of Sorting algo Sub class? Super Class?
  • 28. OOP/AKN/Part_II/28 Examples (contd.) Vehicle Land Vehicle Water Vehicle BoatCar Amphibious Vehicle
  • 29. OOP/AKN/Part_II/29 Inheritance(contd.)  It implies a Generalization/Specialization hierarchy i.e subclass specializes its superclass and superclass generalizes its subclass  Its benefits are Extensibility,Maintainability,Reusability, Understandability,Abstraction, and Substitutability
  • 30. OOP/AKN/Part_II/30 Polymorphism  It is the property that allows to exhibit different behaviours at different situations  Different objects respond differently to a same message Example: message draw Circle responds with drawing a circle Polygon responds with drawing a polygon …
  • 31. OOP/AKN/Part_II/31 Dynamic Binding  (Also called as Late binding) Code associated with a given message will be decided at run time  Helps achieving dynamic polymorphism
  • 32. OOP/AKN/Part_II/32 Object1 Data1+Procedures1 Data Data1 Object3 Data3 + Procedures3 Object2 Data2 + Procedures2 Object4 Data4 + Procedures4
  • 33. OOP/AKN/Part_II/33 Object-Oriented Programming  Is a pool of objects. They interact with each other by passing messages.  Each object implements its own module.
  • 34. OOP/AKN/Part_II/34 Object What we mean? • Humans understand the world by viewing it as composed of autonomous, interacting objects. • Examples: people, animals, phone, desks, buildings, stairs, ...
  • 35. OOP/AKN/Part_II/35 Which is an Object? An object may be of any of the following  A Tangible and/or Visible thing A Table, A Tiger, A Car  Something that may be apprehended intellectually A Bank Account, A Complex Number  Something towards which thought or action is directed A Date, Time
  • 36. OOP/AKN/Part_II/36 Virtual Objects Objects that live in programs only, you can not see by eyes, feel by hand, smell by nose, and taste by tongue. Virtual objects are the basic components for your object-oriented programs.
  • 37. OOP/AKN/Part_II/37 Examples of Virtual Objects Bank Account  Keeps balance; responds to messages to deposit, withdraw, and get balance Set  Elements can be added, deleted, queried for presence. GUI Window  Ultimately responsible for keeping contents of window. Many operations possible including open, close, maximize, minimize, move, etc.
  • 38. OOP/AKN/Part_II/38 Every thing are Objects?  Some objects may be tangible but have fuzzy physical boundaries(fog, river) may not be(sometimes) considered as objects  Difficult to distinguish my fog from your fog  But in a weather map; a fog bank over odisha is a distinctly different object than a fog bank over Maharastra  Beauty, color, emotions(love, anger) may be considered as properties of objects rather than objects.  A Man(an object) loves his wife(another object)  The Cat(an object) is gray
  • 39. OOP/AKN/Part_II/39 Defining an Object An object has state, behavior, and identity; the structure and behavior of similar objects are defined in their common class; the terms instance and object are interchangeable … Grady Booch
  • 40. OOP/AKN/Part_II/40 State The State of an object encompasses all of the properties(static property) of the object plus the current value (dynamic properties) of these properties. … Grady Booch Example: Object :A-320:IC878 (An Air Craft) States: Fuel = 1000 lts Temp = 75 oC Pressure = 200 lbs isStart = false … Dynamic PropertiesStatic Properties
  • 41. OOP/AKN/Part_II/41 The state The state shows the existence of an object When a person is dead, he has no functions, but their DS is still there if he is not burnt. Also called attributes, private space, member variables, instance variables, data members, structure of objects etc…
  • 42. OOP/AKN/Part_II/42 Behavior Example: Object :A-320:IC878 start(…) : if isstart is false, fuel  x lts, … run(…) : if isStart is true, … fly(…) : … stop(…) : if isStart is true, … Similarly: fly causes decreasing in fuel and increasing in temperature i.e change of states
  • 43. OOP/AKN/Part_II/43 Behavior Behavior is how an object acts and reacts, in terms of its state changes and message passing. … Grady Booch Example: Object :A-320:IC878 start, run, fly, break, stop, turn … Behavior of an object is influenced by its state and vice versa
  • 44. OOP/AKN/Part_II/44 Behavior / Method A method is an operation an object can make to respond relevant message. A method is associated with a class. An object invokes a method as a reaction to receipt of a message. When an object has no method, it is dead! Also called member functions, operations, behaviors or services.
  • 45. OOP/AKN/Part_II/45 Message A message is a request to an object to invoke one of its methods. A message therefore contains the name of the method and the arguments of the method. Consequently, invocation of a method is just a reaction caused by receipt of a message. This is only possible, if the method is actually known to the object.
  • 46. OOP/AKN/Part_II/46 Message integer i; /* Define a new object */ i.setValue(1); /* Set its value to 1 */ To express the fact, that the integer object i should set its value to 1. The message is “Apply method setValue with argument 1” (sent to object i). We notate the sending of a message with the help of .(dot)
  • 47. OOP/AKN/Part_II/47 Identity It is that property of an object which distinguishes it from all other objects … Grady Booch Two objects may have same static and dynamic properties. But the identity differentiates them Example: SSN, EmpID, Slno, …
  • 48. OOP/AKN/Part_II/48 Object has State Behavior and identity
  • 49. OOP/AKN/Part_II/49 Class(contd.) It defines a set of objects that share a common structure and behaviors … Grady Booch A class represents only an abstraction, the essence of an object. It doesn't exist in time and space Example: Class Mammal represents the characteristics common to all mammals  To identify a particular Mammal, we say This Mammal or that Mammal
  • 50. OOP/AKN/Part_II/50 Examples of class  Class horse Structure: Age Weight Color Behaviour: Drag Run ride
  • 52. OOP/AKN/Part_II/52 Interface of a Class  The interface of a class provides its outside view and therefore, emphasizes the abstraction while hiding its structure and the secrets of its behavior  The interface primarily consists of the declarations of all operations applicable to its instances  But it may also include the declaration of other classes, constants, variables and exceptions as needed to complete the abstraction
  • 53. OOP/AKN/Part_II/53 Interface(contd.)  The Interface of a class may be divided into three parts 1. Public: declaration that is visible to all the world 2. Protected: declaration that is visible to the class itself, its subclasses, and its friends 3. Private: declaration that is visible only to the class itself and its friends. Also called access specifiers
  • 54. OOP/AKN/Part_II/54 An Example class Time{ public: Time(); void setTime(int,int,int); void printTime(void); private: int hour; int min; int sec; }; Class Name Attributes / Data members Interface messages /member functions Member Access Specifier
  • 55. OOP/AKN/Part_II/55 Example (contd) Time::Time(){hour=min=sec=0;} void Time::setTime(int h, int m, int s){ hour = h; min=m; sec=s; } void Time::printTime(void){ cout<<hour“:”<<min<<“:”<<sec; cout<<endl; } Implementation Constructor Operations / Methods / Member functions
  • 56. OOP/AKN/Part_II/56 Example (contd) main(){ Time t; cout<<“intial time:”; t.printTime(); t.setTime(13,27,6); cout<<“after setting time:”; t.printTime(); } An Object / Instance of Time type Member access operator
  • 57. OOP/AKN/Part_II/57 Instantiation  The mechanism of creating new objects from a class definition is called instantiation mechanism.  Every class has such a mechanism. Static instantiation and Dynamic instantiation. instantiation at compile time; instantiation at run time.  Dynamic instantiation requires a run time support for allocation and de-allocation of memory.
  • 58. OOP/AKN/Part_II/58 Structure vs Class in C++ A structure is simply a class whose members are public by default. class Time{ int hour; int min; int sec; public: Time(); void setTime(int,int,int); void printTime(void); }; struct Time{ int hour; int min; int sec; public: Time(); void setTime(int,int,int); void printTime(void)}; Public by default Private by default
  • 59. OOP/AKN/Part_II/59 Other Definitions for Objects Anything, real, or abstract, about which we store data and those methods (operations) that manipulate the data.” …Martin/Odell  An object is an instance of a class. It can be uniquely identified by its name and it defines a state which is represented by the values of its attributes at a particular time. …Peter Müller
  • 60. OOP/AKN/Part_II/60 Constructors Constructor is used to initialize(reserves memory as well as set values to the data members) an object and it is recognized by having the same name as the class. Constructors can be overloaded i.e. there may be more than one constructors for the same class with several ways of initialization Example: Time(), Time(int), Time(int,int,int), …
  • 61. OOP/AKN/Part_II/61 Constructors  Every time an object is created, one constructor is invoked  Constructors with no arguments is known as the default constructor  Constructor can‟t have a return type  It should always be declared in public part of the class structure. (?)  If no constructor is provided by the programmer then compiler provides one default constructor. ClassName(){}
  • 62. OOP/AKN/Part_II/62 Destructors  It is a special member function named same as the class and preceded by a ~ Example: class Time{ … public: ~Time(); }  It is used to free the state of an object  These are called implicitly when an automatic object goes out of scope. But if an object is initialized using new than it has to be deleted  In very unusual situations does the user need to call a destructor explicitly!
  • 63. OOP/AKN/Part_II/63 Design a class ComplexNum with Attributes real (double), img (double) and Member Functions Default constructor, parameterized constructor printComplex, addComplex Write a main function in which three objects are created. Two of them using parameterized constructor, one using default constructor. Now add first two objects using addComplex member function and store the result in third complex number. Finally print all the complex numbers.
  • 64. OOP/AKN/Part_II/64 Complex number Program class ComplexNum{ private: double real; double img; public: ComplexNum(){real=img=0.0;} ComplexNum(double r, double i){ real = r; img = i; } void printComplex(); ComplexNum addComplex(ComplexNum); }; // end of class definition
  • 65. OOP/AKN/Part_II/65 Main Function main(){ ComplexNum c1(4,5); ComplexNum c2(3,4); ComplexNum c3; c3 = c1.addComplex (c2); c1.printComplex(); c2.printComplex(); c3.printComplex(); }
  • 66. OOP/AKN/Part_II/66 Method implementation void ComplexNum::printComplex() { cout<<real<<“+ i ”<< img <<endl; } ComplexNum ComplexNum:: addComplex( ComplexNum x) { ComplexNum z; z.real = x.real + real; z.img = x.img + img; return z; }
  • 67. OOP/AKN/Part_II/67 Constant Member Functions int func(…) const;  const is a specifier, which specifies that, this function will not modify the states of an object.  The value of the object can‟t be changed  The keyword is written after the parentheses Example: class Date{ private: int d,m,y; public: int day()const{return d;} int month()const{return m;}
  • 68. OOP/AKN/Part_II/68 Constant Member Functions(contd.) int year()const; int addYear(int); };// end of class definition int Date::year() const{return y++;} // Error: Attempt to change value of y int Date::year() const{return y;} // Ok int Date::year() {return y;} // Error: const keyword missing int Date::addYear(int a){return y+a;} // Ok
  • 69. OOP/AKN/Part_II/69 Constant Member Functions(contd.) • A constant member function can be invoked for both constant and non-constant objects. • A non constant member function can be invoked only for non-constant objects. Example: void f(Date &d, const Date& cd){ int i=d.year(); // Ok (one) int k=d.addYear(1); // Ok (two) int l=cd.addYear(1); //Error (two) int m=cd.year(); //Ok(two) }
  • 70. OOP/AKN/Part_II/70 Static Class Members Static data member is an attribute that is a part of class, yet is not a part of an object In other words there is exactly one copy of a static member instead of one copy per object A Function that needs access to members of a class, yet does not need to be invoked for a particular object is called static member function
  • 71. OOP/AKN/Part_II/71 Example Static data member class Sclass{ int x, y; static int z; . . . }; int Sclass::z; main() { Sclass o, p, q; } o x y p x y q x y z
  • 72. OOP/AKN/Part_II/72 Example: Number of objects that are live in any point of the program class Employee{ char* name; static int count; // static data memb. public: Employee(char*); char* getName(); static int getCount(); // static memb. func ~Employee(); };
  • 73. OOP/AKN/Part_II/73 Example (contd) int Employee::count=0; int Employee::getCount() {return count;} Employee::Employee(char* N){ name=new char[strlen(N)+1]; strcpy(name,N); ++count; }
  • 74. OOP/AKN/Part_II/74 Example (contd) Employee::~Employee(){ delete [] name; --count; } char* Employee::getName(){ return name; } main(){ cout<<“no of Employees: “<< Employee::getCount()<<endl; Employee* e1=new Employee (“Bob”); Employee* e2=new Employee (“John”);
  • 75. OOP/AKN/Part_II/75 Example (contd) cout<<“no of employees: “ <<e1->getCount(); cout<<“Emp1: “<<e1->getName(); cout<<“Emp2: “<<e2->getName(); delete e1; cout<<“no of employees: “ <<e2->getCount(); delete e2; cout<<“no of employees: “ <<Employee::getCount(); }
  • 76. OOP/AKN/Part_II/76 Static Class Members  Static data members are accessible by both static and/or non-static member functions  Static member functions can only access the static class members  To access a public static class member, simply prefix the class name and scope resolution operator  To access a private static class member, when no object exists take help of a static member function otherwise non-static could be used.
  • 77. OOP/AKN/Part_II/77 Contents Operator Overloading Friend Functions Data Conversion Copying Objects this pointer Friend class Nested class A Complete Example
  • 78. OOP/AKN/Part_II/78 Overloading Operators  Operator Overloading allows us to overload the existing operators s.t. they can have operands as objects Complex C=A+B;//A & B are complex number objs  It doesn't provide any means to create new operators  Some operators Can‟t be overloaded  Binary operators may be overloaded either by a non-static member function having one argument or a non-member function having two arguments
  • 79. OOP/AKN/Part_II/79 Example: Distance class class Distance{ int feet; float inches; public: Distance():feet(0),inches(0.0){} Distance(int f, float i):feet(f), inches(i){} void showDistance(){ cout<<feet<<„‟‟<<inches<<„”‟<<endl;} Distance addDistance(Distance); };
  • 80. OOP/AKN/Part_II/80 Example (contd.) Distance Distance::addDistance(Distance d){ Distance res; res.feet=feet+d.feet; res.inches=inches+d.inches; if(res.inches>=12.0){ res.inches-=12.0; res.feet ++; } return res; }
  • 81. OOP/AKN/Part_II/81 Overloading + Operator class Distance{ int feet; float inches; public: Distance():feet(0),inches(0.0){} Distance(int f, float i):feet(f), inches(i){} void showDistance(); Distance operator+(Distance); };
  • 82. OOP/AKN/Part_II/82 Example (contd.) Distance Distance::operator+(Distance d){ int f=feet+d.feet; float i=inches+d.inches; if(i>=12.0){ i-=12.0; f++; } return Distance(f,i); }
  • 83. OOP/AKN/Part_II/83 Example (contd.) main(){ Distance d1(10,6), d2(11,7); Distance d3=d1+d2; d1.showDistance(); d2.showDistance(); d3.showDistance(); Distance d4=d1+d2+d3; d4.showDistance(); } 10’ 6” 11’ 7” 22’ 1” 43’ 2”
  • 84. OOP/AKN/Part_II/84 Task Overlaod + and – operators for ComplexNum class Design the class Define functions Main function
  • 85. OOP/AKN/Part_II/85 Passing two args: a non member function class Distance{ int feet; float inches; public: Distance(); Distance(int, float); void showDistance(); }; Distance operator+(Distance, Distance);
  • 86. OOP/AKN/Part_II/86 Example (contd.) Distance operator+(Distance d1, Distance d2){ int f = d1.feet+d2.feet; float i = d1.inches+d2.inches; if(i>=12.0){ i-=12.0; f++; } return Distance(f,i); } Illegal Accessing private data members
  • 87. OOP/AKN/Part_II/87 A solution: with a non member function class Distance{ int feet; float inches; public: Distance(); Distance(int, float); void showDistance(); int getFeet(){return feet;} float getInch(){return inch;} }; Distance operator+(Distance, Distance);
  • 88. OOP/AKN/Part_II/88 Passing Two Args Distance operator+(Distance d1, Distance d2){ int f=d1.getFeet()+d2.getFeet(); float i=d1.getInch()+d2.getInch(); if(i>=12.0){ i-=12.0; f++; } return Distance(f,i); } Note: In one program, there should be only one operator overloading function for each operator. Remember that this function should be a non-member!
  • 89. OOP/AKN/Part_II/89 Friend Function  A friend of a class is a function that is not a member of the class but is permitted to use the private and protected members of the class  The name of the friend is not in the scope of the class and the friend is not called with the member access operator  It can be declared in either private or public part of a class  A friend is explicitly declared inside the class declaration of which it is a friend  Key word is friend
  • 90. OOP/AKN/Part_II/90 Friend Function Example class Sample{ int a; int b; public: Sample(int x,int y):a(x),b(y){} friend float mean(Sample s){ return float(s.a+s.b)/2.0; } };
  • 91. OOP/AKN/Part_II/91 Example (contd.) main(){ Sample test(13,10); cout<<“mean is:”<<mean(test); } What is the use?  If it is required to to operate on private members of two different and unrelated classes then friend to both classes will help.  It can be helpful in operator overloading
  • 92. OOP/AKN/Part_II/92 Overloading using friend function class Distance{ int feet; float inches; public: Distance(); Distance(int, float); void showDistance(); friend Distance operator+(Distance, Distance); };
  • 93. OOP/AKN/Part_II/93 Example (contd.) Distance operator+(Distance d1, Distance d1){ int f = d1.feet+d2.feet; float i = d1.inches+d2.inches; if(i>=12.0){ i-=12.0; f++; } return Distance(f,i); } Legal Accessing private data members as it is a friend function
  • 94. OOP/AKN/Part_II/94 Example (contd.) main(){ Distance d1(10,6), d2(11,5); Distance d3=d1+d2; d1.showDistance(); d2.showDistance(); d3.showDistance(); Distance d4=d1+d2+d3; d4.showDistance(); }
  • 95. OOP/AKN/Part_II/95 Example  Matrix Vector product class Matrix; class Vector{ float v[4]; … friend Vector operator* (Matrix &,Vector &); }; class Matrix{ Vector m[4]; … friend Vector operator*(Matrix&, Vector&); };
  • 96. OOP/AKN/Part_II/96 Example (Contd.) Vector operator *(Matrix& mat, Vector& vec) { Vector res; for(int i=0;i<4;i++){ res.v[i]=0; for(int j=0;j<4;j++) res.v[i]+=mat.m[i].v[j]*vec.v[i]; } return res; } //Complete the program and execute
  • 97. OOP/AKN/Part_II/97 Task Overlaod + and – operators for ComplexNum class using non-member(friend) functions. Design the class Define functions Main function
  • 98. OOP/AKN/Part_II/98 A Comparison Access to private part Inside scope of the class Invoked with reference to an object Member function Yes Yes Yes Static - member Yes Yes Optional Friend function Yes No No
  • 99. OOP/AKN/Part_II/99 Unary Operators A Unary operator can be defined by either a member function taking no arguments or a non-member function taking one argument Example class X{ operator ++(); //prefix operator ++(int); //postfix }
  • 100. OOP/AKN/Part_II/100 Example (contd.) The int argument is simply a dummy argument. It is used to distinguish between a prefix and postfix application Example void operator ++(int){//postfix feet++; } void operator ++(){//prefix ++feet; } d1++; d1.showDistance( ); ++d2; d2.showDistance( );
  • 101. OOP/AKN/Part_II/101 Mixed mode overloading How to execute when two operands are of different type? Complex c,c1; double d; c+=c1; c+=d; c=d+c1; c=c1+d; Complex operator +=(Complex a){ re+=a.re; im+=a.im; return *this; } Member function
  • 102. OOP/AKN/Part_II/102 Overloading(contd.) Complex operator +=(double a){ re+=a; return *this; } }; //end of class Complex operator +(double a, Complex b){ complex r=b; return r+=a; } Non-Member function Member function
  • 103. OOP/AKN/Part_II/103 Overloading(contd.) Complex operator +(Complex a, double b){ complex r=a; return r+=b; } Task Complete the above program with all possible types of operator overloading with mixed mode arithmetic. Non-Member function
  • 104. OOP/AKN/Part_II/104 Example main(){ Complex c1, c2; cin>>c1; cin >>c2; Complex c3=c1+c2; cout<<c1<<endl; cout<<c2<<endl; Complex c4=c1+c2+c3; cout<<c4<<endl; } Error
  • 105. OOP/AKN/Part_II/105 Overloading Stream Insertion and extraction operators class Complex{ … friend ostream& operator<<(ostream&, Complex); friend istream& operator>>(istream&, Complex&); }; ostream& operator<<(ostream& out, Complex c){ out<<c.re<<“ + i”<<c.img<<endl; return out;}
  • 106. OOP/AKN/Part_II/106 Operator overloading istream& operator>>(istream& in, Complex &c){ in>>c.re>>c.img; return in; }  These functions must be non members as the objects of class Complex appears in each case as the right operand and the function can not be a part of class ostream and istream
  • 107. OOP/AKN/Part_II/107 Data Conversion  „=„ is a special operator with complex properties.  When both sides are of equal type, the compiler does not need any special instructions to operate.  If they are different ? Conversion between Basic Types: (int)=(float); //allowed  Each such conversion has its own routine, built into the compiler. This is called an implicit conversion(casting).
  • 108. OOP/AKN/Part_II/108 Data Conversion (contd.)  Sometimes we need explicit casting like float ..= float(int ..)  This conversion also use the built-in routines available with the compiler.  User Defined to Basic Types float ..=float(Distance); float f = d1; Operator float(){ float ft=inches/12; ft+=float(feet); return ft;}
  • 109. OOP/AKN/Part_II/109 Data Conversion(contd.)  Basic to User-defined type Distance d1=2.35; Distance(float f){ feet=int(f); inches=12*(f-feet); }  User-defined to User-defined type objA=objB;//both are objects of different classes
  • 110. OOP/AKN/Part_II/110 Data Conversion(contd.) class Rect{ double xco; double yco; public: … } class Polar{ double radius; double angle; public: …
  • 111. OOP/AKN/Part_II/111 Data Conversion(contd.) operator Rect(){ double x=radius*cos(angle); double y=radius*sin(angle); return Rect(x,y); } //inside class declaration }; //class ends here main(){ Rect rec; Polar pol(10.0,0.785398); rec=pol; pol.display(); rec.display();}
  • 112. OOP/AKN/Part_II/112 Pitfalls/Guidelines of Data Conversion Use Similar meanings Use overload operators to perform similar operations as in basic types Use Similar Syntax Don‟t try to create new operators also don‟t design binary operators for unary action and vice versa Show Restraint Don‟t overload operators if not required frequently. Also Limit the overloaded operators for a class to manage complexity
  • 113. OOP/AKN/Part_II/113 Pitfalls/Guidelines of Data Conversion Avoid Ambiguity Don‟t try to overload the same operator in many different ways in a same program. This may be a confusion for the compiler. Not All operators can be overloaded. *(pointer), .(access op), :: (scope), ?: (ternary), and sizeof()
  • 114. OOP/AKN/Part_II/114 Copying Objects class Table{ char *name; float size; public: Table(float s=15){ name=new char[size=s];} }; 1.Table t1; 2.Table t2=t1; 3.Table t3; 4.t3=t2; 5.Table t4(t3); Default Constructor //constructor is called //copy initialization //constructor is called //copy assignment //copy constructor
  • 115. OOP/AKN/Part_II/115 Copying Objects (contd.)  Line 1: default constructor is called and the address for the memory allocated is stored in name variable.  Line 2: It is initialized by copying. i.e memberwise copying t2.name=t1.name;  Now both object point to same memory area.  Line 3: default constructor is called and the address for the memory allocated is stored in name variable.(t3.name)  Line 4: t3.name is overwritten by t2.name which is nothing but t1.name  Line 5: . . .
  • 116. OOP/AKN/Part_II/116 Copying Objects (contd.) Conclusion: 1. Storage for t3 is lost to program for ever 2. All objects point to same memory area 3. Destructor will be called Four times(?) i.e. the same memory area will be deleted four times and the result is undefined( may be disastrous!) Also called as shallow copy
  • 117. OOP/AKN/Part_II/117 Copy Constructors Make a duplicate copy of an object of the same class, the default make a memberwise copy of the the object The default Copy constructors is created by the compiler automatically. A local copy of the object is constructed which may create anomalies. Copy constructors can also be defined by us, which can be designed meaning fully according to the requirement.
  • 118. OOP/AKN/Part_II/118 Copy Constructors(Deep Copy) class Table{ . . . Table (const Table&); Table& operator=(const Table&); }; Table::Table(const Table& t){ name=new char[size=t.size]; strcpy(name,t.name); } Copy constructor Copy assignment
  • 119. OOP/AKN/Part_II/119 Copy Constructors(contd.) Table& operator=(const Table& t){ if(this!=&t){ delete name; name=new char[size=t.size]; strcpy(name,t.name); } return *this; }  Why copy constructor takes the argument as const and a reference?
  • 120. OOP/AKN/Part_II/120 The “This” Pointer Every object has access to its own address through a pointer called „this‟ The this pointer is passed as an implicit first argument on every non-static member function call for an object. The this pointer is implicitly used to refer both the data and function members of an object It can also be used explicitly; Example: (*this).x=5; or this->x=5;
  • 121. OOP/AKN/Part_II/121 Friend Classes  If a class is declared as friend to another class then it is allowed to access all the members of that class  To declare class A as a friend of class B, place the corresponding declaration in the definition of class B. Example: class ClassOne{ ... friend ClassTwo; };  Friendship is neither symmetric nor transitive. ClassTwo is allowed to access all the members of ClassOne
  • 122. OOP/AKN/Part_II/122 Nested Classes Classes like blocks and namespaces can be nested. These are all scopes and nesting allows local hiding of names and local allocation of resources. This is often the case when a class is needed as part of the implementation of a larger construct
  • 123. OOP/AKN/Part_II/123 Nested Classes (Contd.) char c; //::c class X{ char c; //X::c public: class Y{ char c; //X::Y::c public: void foo(char e){ X t; ::c=t.X::c=c=e;} }; };
  • 124. OOP/AKN/Part_II/124 Local / Global classes  Class declared out of all scopes are called global class. These classes may be used to create objects anywhere in the program. Class declared inside a scope (function etc) are called local class. Objects of this class can be used inside the specified scope only.
  • 125. OOP/AKN/Part_II/125 A more complete example class String{ int length; char *ptr; void setString(const char*); public: String(const char* = ““); String(const String&); ~String(); String& operator=(const String&); String& operator +=(const String &); bool operator !()const; bool operator ==(String&)const;
  • 126. OOP/AKN/Part_II/126 Example (contd.) bool operator <(String)const; bool operator !=(String&)const; bool operator >(String&)const; bool operator <=(String&)const; bool operator >=(String&)const; char& operator[](int); String operator()(int,int); int getLength()const; friend ostream& operator<<(ostream&, const String&); friend istream& operator>>(istream&, String&); }; //end of class def.
  • 127. OOP/AKN/Part_II/127 Example (contd.) void String::setString(const char *s2){ ptr=new char[length+1]; strcpy(ptr,s2);} String::String(const char* s){ length=strlen(s); setString(s);} String::String(String& copy){ length=copy.length; setString(copy.ptr);} String::~String(){delete []ptr;}
  • 128. OOP/AKN/Part_II/128 Example (contd.) String& String::operator=(String& right){ if(&right!=this){ delete [] ptr; length=right.length; setString(right.ptr); } return *this; } String& String::operator+=(String& right){ char *tmp=ptr; length+=right.length; ptr=new char[length+1]; strcpy(ptr,tmp); strcat(ptr,right.ptr); delete [] tmp; return *this; }
  • 129. OOP/AKN/Part_II/129 Example (contd.) bool String::operator!()const{ return length==0;} bool String::operator==(String& right)const{ return strcmp(ptr,right.ptr)==0;} bool String::operator<(String right)const{ return strcmp(ptr,right.ptr)<0;} bool String::operator!=(String& right)const{ return !(*this==right);}
  • 130. OOP/AKN/Part_II/130 Example (contd.) bool String::operator>(const String& right)const{ return right<*this; } bool String::operator<=(const String& right)const{ return !(right<*this); } bool String::operator>=(const String& right)const{ return !(*this<right); }
  • 131. OOP/AKN/Part_II/131 Example (contd.) char& String::operator[](int sbsrpt){ if(sbsrpt>=0 && sbsrpt<length) return ptr[sbsrpt]; } String String::operator()(int i,int l){ if(i>=0 && i<length && l>=0 ) int len; if((l==0)||(i+l>length)) len=length-i; else len=l; char* tmp=new char[len+1]; strncpy(tmp,&ptr[i],len); tmp[len]=„0‟; String tmpString(tmp); delete[]tmp; return tmpString;}
  • 132. OOP/AKN/Part_II/132 Example (contd.) int String::getLength()const{ return length; } ostream& operator<<(ostream& out, const String& s){ out<<s.ptr; return out; } istream& operator>>(istream& in, String& s){ char tmp[500]; in>>tmp; s=tmp; return in;}
  • 133. OOP/AKN/Part_II/133 Example (contd.) #include<iostream> #include<cstring> main(){ String s1(“Happy”), s2(“birthday”),s; cout<<(s2==s1?”true”:”false”)<<endl; cout<<(s2!=s1?”true”:”false”)<<endl; cout<<(s2>s1?”true”:”false”)<<endl; cout<<(s2>=s1?”true”:”false”)<<endl; cout<<(s2<=s1?”true”:”false”)<<endl; if(!s){cout<<“empty”; s=s1;cout<<s;}
  • 134. OOP/AKN/Part_II/134 Example (contd.) s1+=s2; cout<<s1 <<endl; s1+=“ to you”; cout<<s1<<endl; cout<<s1(0,14)<<endl; String *s4ptr=new String(s1); cout<<*s4ptr; S1[0]=„H‟;s1[6]=„B‟; cout<<s1; }
  • 135. OOP/AKN/Part_II/135 Task  Design a class called LargeInt to handle integers of large size (O(103 ) digits)  overload all arithmetic operators (+, -, *, /, %)  overload all unary (++, --, +=, . . .) operators  overload all relational operators  design copy constructor and copy assignment  Member function to test primality  Write a suitable main function to demonstrate all above facilities
  • 136. OOP/AKN/Part_II/136 Readings Programming  Bjarne Stroustrup, The C++ Programming Language, PE  Lippman, Lajoie, C++ Primer, Addison-Wesley  B. Eckel, Thinking in C++, Vol I and Vol II  Deitel & Deitel, C++ How to program  Schildt, C++ The complete reference  S. Sahay, OOP with C++  E. Balagurusami, Object oriented programming with C++ Concepts  G.Booch, Object Oriented Analysis & Design  Bertand Meyer, Object Oriented Software Construction