Date post: | 22-Jan-2018 |
Category: |
Engineering |
Upload: | ajit-nayak |
View: | 184 times |
Download: | 3 times |
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 WordsWord List Flag
Words Words(prev,curr)
WordWord Words
getSortedWordList countDiffWords printResult
Sorted WordsSorted Words
CountCount
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
ProgramProcedure
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
Procedure1Procedure2 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/Specializationhierarchy
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
ObjectWhat 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 increasingin 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
MessageA 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 horseStructure:
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 viewand 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
Interfacemessages /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 addComplexmember function and store the result in third complex number.
Finally print all the complex numbers.
OOP/AKN/Part_II/64
Complex number Programclass 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 implementationvoid 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 Functionsint 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 memberclass 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
ContentsOperator 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 argumentor a non-member function having two arguments
OOP/AKN/Part_II/79
Example: Distance classclass 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 + Operatorclass 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 ArgsDistance 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
Exampleclass 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 OperatorsA 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 overloadingHow 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
operatorsclass 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 overloadingistream& 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 implicitconversion(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 Typesfloat ..=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 Objectsclass 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 memberwisecopying 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 ConstructorsMake 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 exampleclass 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
ReadingsProgramming 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