34
UNIT III Overloading 05/16/22 1 VIT - SCSE By G.SasiKumar., M.E., (Ph.D)., Assistant Professor School of Computing Science and Engineering VIT University

14 operator overloading

Embed Size (px)

DESCRIPTION

operator overloading

Citation preview

Page 1: 14 operator overloading

UNIT III Overloading

04/10/231 VIT - SCSE

By

G.SasiKumar., M.E., (Ph.D).,Assistant Professor

School of Computing Science and EngineeringVIT University

Page 2: 14 operator overloading

Functions in C++Experience has shown that the best way to

develop and maintain large programs is to construct it from smaller pieces (Modules)

This technique Called “Divide and Conquer”

•Easer To

DesignBuildDebugExtendModifyUnderstandReuseBetter Organization

Wise Development Approach

main(){ ----- ----}

function f1(){ --- ---}

function f2(){ --- ---}

Page 3: 14 operator overloading

Function Overloading

C++ supports writing more than one function with the same name but different argument lists. This could include:different data typesdifferent number of arguments

The advantage is that the same apparent function can be called to perform similar but different tasks. The following will show an example of this.

Page 4: 14 operator overloading

Function Overloadingvoid swap (int *a, int *b) ;

void swap (float *c, float *d) ;

void swap (char *p, char *q) ;

int main ( )

{

int a = 4, b = 6 ;

float c = 16.7, d = -7.89 ;

char p = 'M' , q = 'n' ;

swap (&a, &b) ;

swap (&c, &d) ;

swap (&p, &q) ;

}

void swap (int *a, int *b)

{ int temp; temp = *a; *a = *b; *b = temp; }

void swap (float *c, float *d)

{ float temp; temp = *c; *c = *d; *d = temp; }

void swap (char *p, char *q)

{ char temp; temp = *p; *p = *q; *q = temp; }

Page 5: 14 operator overloading

04/10/235 VIT - SCSE

• Operator Overloading refers to giving the normal C++ Operators, such as +,*,<= etc., additional meanings when they are applied to user defined data types.

• Simply defined as to create new definitions for operators.

Syntax :<ret.datatype> operator <operator name>(){------}

Operator Overloading

Page 6: 14 operator overloading

The steps involved an operator are :

1. Create a class that defines a data type that is to be

used in the overloading operation

2. Declare the operator function as either a member

function or a friend function inside the class

3. Define the operator function either inside or outside

the class

4. Use the operator in the main() function

Page 7: 14 operator overloading

• All the operators can be overloaded using friend

function except () [] -> and =. These operators must be

defined by using a member function.

ASSIGNMENT OPERATOR OVERLOADING RULES :

• The operator function for the assignment operator are

inherited by any derived class.

• Friend functions cannot be used to overload the

assignment operator

Page 8: 14 operator overloading

The operators that can be overloaded are

+ - * / % ^ & | _ != < > <= >= += -+ *= != ++ -- [ ] () || &= && -> , new delete

The operators that cannot be overloaded are # .(member operator) :: sizeof ?:

Page 9: 14 operator overloading

04/10/239 VIT - SCSE

class sample{private:int x;float y;public:sample(int,float);void operator =(sample s);void display();};sample::sample(int one,float two){x=one;y=two;}

void sample::operator =(sample s){x=s.x;y=s.y;}void sample::display(){cout<<”integer number(x)=:”<<x<<endl;cout<<”floating value(y)=:”<<y<<endl;cout<<endl;}

(Unary)Overloading Assignment Operator (=)

Page 10: 14 operator overloading

04/10/2310 VIT - SCSE

void main(){sample ob1(10,4.5);sample ob2(20,6.2);ob1=ob2;cout<<”contents of the first object \n”;ob1.display();cout<<”contents of the second object \n”;ob2.display();}

Page 11: 14 operator overloading

04/10/2311 VIT - SCSE

class sample{private :int x;public :sample(){x=0;}int getcount(){return x;}sample operator ++(){++x;sample t;t.x=x;return t;}};

void main(){sample s1,s2;cout<<"s1 ="<<s1.getcount()<<endl;cout<<"s2 ="<<s2.getcount()<<endl;++s1;s2=++s1;cout<<"s1 ="<<s1.getcount()<<endl;cout<<"s2 ="<<s2.getcount()<<endl;getch();}

Overloading ++ Operator

OUTPUT :

s1 = 0

s2 = 0

s1 = 2

s2 = 2

Page 12: 14 operator overloading

04/10/2312 VIT - SCSE

class sample{private:int x;public:sample();sample(int);sample operator +(sample s);void display();};sample::sample(){x=0;}

sample::sample(int one){x=one;}sample sample::operator +(sample s){sample t;t.x=x+s.x;return(t);}void sample::display(){cout<<”X=”<<x<<endl;}

(Binary) Overloading Arithmetic Operators (+)

Page 13: 14 operator overloading

04/10/2313 VIT - SCSE

void main(){sample ob1(10);sample ob2(20);sample ob3;ob3=ob1+ob2;ob1.display();ob2.display();ob3.display();} 

OUTPUT :X=10X=20X=30

Page 14: 14 operator overloading

04/10/2314 VIT - SCSE

class sample{private:int x;public:sample();sample(int);sample operator -(sample s);void display();};sample::sample(){x=0;}

sample::sample(int one){x=one;}sample sample::operator -(sample s){sample t;t.x=x-s.x;return(t);}void sample::display(){cout<<”X=”<<x<<endl;}

(Binary) Overloading Arithmetic Operators (-)

Page 15: 14 operator overloading

04/10/2315 VIT - SCSE

void main(){sample ob1(10);sample ob2(20);sample ob3;ob3=ob1-ob2;ob1.display();ob2.display();ob3.display();} 

OUTPUT :X=10X=20X=-10

Page 16: 14 operator overloading

#include<iostream.h>const int SIZE=5;class test{private :int a[SIZE];public:int operator [] (int i){return i;}};void main(){test t1;int i;

OVERLOADING THE SUBSRIPTOPERATOR [ ]

for(i=1;i<=SIZE;i++){// control is transferred to the operator function call int operator [] (int i)

cout<<t1[i]<<"\t";}}

OUTPUT :12345

Page 17: 14 operator overloading

04/10/2317 VIT - SCSE

class sample{private:int x;public:sample();sample(int one);void display();int operator <(sample s);};sample::sample(){x=0;}sample::sample(int one){x=one;}

void sample::display(){cout<<"X="<<x<<endl;}int sample::operator <(sample s){return (x<s.x);}void main(){sample ob1(20);sample ob2(100);cout<<(ob1<ob2)<<endl;cout<<(ob2<ob1)<<endl;getch();}

Overloading Arithmetic Comparison Operators (<)

OUTPUT :10

Page 18: 14 operator overloading

04/10/2318 VIT - SCSE

class sample{private:int x;public:sample();sample(int);sample operator +=(sample s);void display();};sample::sample(){x=0;}sample::sample(int one){x=one;}

sample sample::operator +=(sample s){return(x+=s.x);}void sample::display(){cout<<"X="<<x<<endl;}void main(){sample ob1(10);sample ob2(20);ob1.display();ob2.display();ob2+=ob1;ob1.display();ob2.display();}

Overloading Compound Assignment Operator (+=)

OUTPUT :X=10X=20X=10X=30

Page 19: 14 operator overloading

04/10/2319 VIT - SCSE

class sample{private:int x;public:sample();sample(int one);void display();int operator <=(sample s);};sample::sample(){x=0;}sample::sample(int one){x=one;}

void sample::display(){cout<<"X="<<x<<endl;}int sample::operator <=(sample s){return (x<=s.x);}void main(){sample ob1(20);sample ob2(100);cout<<(ob1<=ob2)<<endl;cout<<(ob2<=ob1)<<endl;getch();}

Overloading Compound Assignment Operator (<=)

OUTPUT :10

Page 20: 14 operator overloading

Increment and Decrement Operators

We have used n++; and ++n; to replace for n = n + 1;

and we have used --n and n--; to replace for n = n - 1;

The expressions n++ and ++n have values.The expression n++ returns the value of n before

to incrementing, then increments the value of n.++n increments the value of n, then returns the

incremented value.The expressions n-- and --n have values as well.The expression n-- returns the value of n before to

decrementing, then decrements the value of n.--n decrements the value of n, then returns the

decremented value.

Page 21: 14 operator overloading

Overloading ++ and - -

With C++, you use ++ to increment variables, and - - to decrement variables

When a prefix operator such as ++ is used in an expression, the mathematical operation takes place before the expression is evaluated

When the postfix operator is used, the expression is evaluated before the mathematical operation takes place

Page 22: 14 operator overloading

Using the Prefix and Postfix ++ Operators with an Integer

Page 23: 14 operator overloading

Generic Programming for Templates

A methodology for the development of reusable software libraries

Three primary tasks:Categorize the abstractions in a domain into

conceptsImplement generic algorithms based on the

conceptsBuild concrete models of the concepts

Concepts make templates easier to useExpress requirements directly in code

Provide complete type-checking of templates

Page 24: 14 operator overloading

Characteristics of Generic Libraries

Reusable: able to operate on user-defined data types

Composable: able to operate on data types defined in another library

Efficient: performance on par with non-generic, hand-coded implementations

Page 25: 14 operator overloading

C++ Templates

C++ Function Templates

-- C++ Function templates are those functions which can handle different data types without separate code for each of them. 

C++ Class Templates

-- C++ Class Templates are used where we have multiple copies of code for different data types with the same logic.

Page 26: 14 operator overloading

Templates

Constructs a family of related functions or class

Different Approach – Function

   Example 1 & 2 : int Add(int a,int b) { return a+b;} // function Without C++ template

float Add(float a, float b) { return a+b;} // function Without C++ template

1. Naïve ApproachDifferent Function Definitions

Different Function Names

2. Function OverloadingDifferent Function Definitions

Same Function Name

3. Template FunctionsOne Function Definition (a function template)

Compiler Generates Individual Functions

Page 27: 14 operator overloading

Approach 3: Function Template• A C++ language construct that allows the compiler to generate multiple versions of a function by allowing parameterized data types.

Template < TemplateParamList >FunctionDefinition

FunctionTemplate

TemplateParamDeclaration: placeholder

class typeIdentifier typename variableIdentifier

Page 28: 14 operator overloading

Example of a Function Template

 template<class T>

T Add(T a,T b)//C++ Fucntion Template sample{ return a+b;}

Template parameter

(class, user defined type, built-in types)

Page 29: 14 operator overloading

Class Template• A C++ language construct that allows the compiler to generate multiple versions of a class by allowing parameterized data types.

Template < TemplateParamList >ClassDefinition

Class Template

TemplateParamDeclaration: placeholder

class typeIdentifier typename variableIdentifier

Page 30: 14 operator overloading

Example of a Class Template

template<class ItemType>class GList{ public: bool IsEmpty() const; bool IsFull() const; int Length() const; void Insert( /* in */ ItemType item ); void Delete( /* in */ ItemType item ); bool IsPresent( /* in */ ItemType item ) const; void SelSort(); void Print() const; GList(); // Constructor private: int length; ItemType data[MAX_LENGTH];};

Template parameter

Page 31: 14 operator overloading

Advantages of C++ Class Templates: 

One C++ Class Template can handle different types of parameters.

Compiler generates classes for only the used types. If the template is instantiated for int type, compiler generates only an int version for the c++ template class.

Templates reduce the effort on coding for different data types to a single set of code.

Testing and debugging efforts are reduced.

Page 32: 14 operator overloading

Standard Template Library

In the late 70s Alexander Stepanov first observed that some algorithms do not depend on some particular implementation of a data structure but only on a few fundamental semantic properties of the structure

Developed by Stepanov and Lee at HP labs in 1992

Become part of the C++ Standard in 1994

Page 33: 14 operator overloading

What’s in STL?Container classes: vector, list, deque, set,

map, and etc…A large collection of algorithms, such as

reverse, swap, heap, and etc.VectorA sequence that supports random access to

elementsElements can be inserted and removed at the

beginning, the end and the middleConstant time random accessCommonly used operations

begin(), end(), size(), [], push_back(…), pop_back(), insert(…), empty()

Page 34: 14 operator overloading

Recap

Templates are mechanisms for generating functions and classes on type parameters. We can design a single class or function that operates on data of many types

function templatesclass templates