Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
160 views

Operator Overloading Programs.

Operator overloading allows redefining operators like +, -, etc. for user-defined types. This allows behaviors like adding two distance objects. There are two types of operator overloading - unary for operators like ++ that take one operand, and binary for operators like + that take two operands. Binary operators can be overloaded to perform tasks beyond their default behavior, like adding distances and converting inches to feet.

Uploaded by

vickra
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
160 views

Operator Overloading Programs.

Operator overloading allows redefining operators like +, -, etc. for user-defined types. This allows behaviors like adding two distance objects. There are two types of operator overloading - unary for operators like ++ that take one operand, and binary for operators like + that take two operands. Binary operators can be overloaded to perform tasks beyond their default behavior, like adding distances and converting inches to feet.

Uploaded by

vickra
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 14

/*operator overloading:

=> Allow us to give additional meanings to the normal C++ operators like
+,-,++,--,+=,-=, etc.

=> Help us in redefining the C++ language.

=> We can change the functionality of operators to whatever we wants.

=> Used in combination with classes and fuctions.

=> Operator overloading is not only advantagious, but it also have some
dangerous effects, which we will discuss later. */
 There are two types of overloading.
 1. Overloading Unary Operators.
 2. Overloading Binary Operators.

// Overloading Unary Operators.


#include<iostream.h>
#include<conio.h>

class counter
{
private:
unsigned int count;
public:
counter()
{
count=0;
}
unsigned int get_count()
{
return count;
}
void operator ++() // Operator ---> keyword.
{ // ++() is used as the function which will
++count; // will increament the value of count, each
} // time it is called.
};
// we also can use ++ operator for reducing
int main() // the value of the variable count.
{ // single operator like + and - can also
clrscr(); // be used.
counter c1,c2;
cout<<"c1= "<<c1.get_count()<<endl;
cout<<"c2= "<<c2.get_count()<<endl;

++c1;
++c1;
++c2;

cout<<"c1= "<<c1.get_count()<<endl;
cout<<"c2= "<<c2.get_count();

//return 0;
getch();
}

/*
The fuction, which contain the definition of the operator overloading
will increament or dicreament (increament in this case) the variable of
the class data type(here the class type is "counter" and the variables
c1 and c2 are also of the counter type.

if traditional data types like int,float and char etc are increamented
with the same operator, the operator will perform its default operation.*/

/*
In previous programe, we can't do the following.

c1=++c2;

the reason is that we have defined the overloading function with the void
return type. to make it possible, the return type of the overloading function
must be changed to the type of the returning value.
As here we assign the increamented value(with help of overloading operator)
to c1, which datatype is "counter", the class type, so we will have to change
the return type of the overloading function to the "counter" datatype. */

//Program to show that "Operator Retruns Value".

#include<iostream.h>
#include<conio.h>

class counter
{
private:
unsigned int count;

public:
counter():count(0)
{
}

unsigned int get_count()


{
return count;
}

counter operator ++() //the return type of the overloading function


{ // is changed to "counter", the class datatype.
++count;

counter temp; // we have assigned the value of the "count"


temp.count=count; //variable to another counter type variable, named
return temp; // "temp". this value is returned, when the
// function is called.
}

};

int main()
{
clrscr();

counter c1,c2;
cout<<"c1= "<<c1.get_count()<<endl;
cout<<"c2= "<<c2.get_count()<<endl;

++c1; //the value of "count" variable is increamented by 1.

c2=++c1; //value of "count" is again increamented and assigned


// to the "counter" type variable c2.

cout<<"c1= "<<c1.get_count()<<endl;
cout<<"c2= "<<c2.get_count();
getch();
}

/* NAMELESS TEMPORARY CONSTRUCTORS.

In previous program, we returned an object value of the "counter" type


from the overloading function, by typing the following commonds.

counter temp;
temp.cout=count;
return temp;
these steps are performed only to return a value of the counter type to the
calling function. We can perform this operation using simple method, by
creating "Nameless Temporary Constructor".

the following program shows the use of "Nameless temporary Constructor".


*/

//Program to show that "Nameless Temporary Constructor".

#include<iostream.h>
#include<conio.h>

class counter
{
private:
unsigned int count;

public:
counter():count(0)
{
}

counter(int c): count(c) // Whenever we need to pass or return a


{ // value of the object from the class, we
} // do it only with help of single arg constructor.

unsigned int get_count()


{
return count;
}
counter operator ++()
{
++count;

return counter(count); // A temporary no named (nameless) object with


} // "counter" return type is created and returned
}; // to the calling function(overloading func).

int main()
{
clrscr();

counter c1,c2;
cout<<"c1= "<<c1.get_count()<<endl;
cout<<"c2= "<<c2.get_count()<<endl;

++c1; //the value of "count" variable is increamented by 1.

c2=++c1; //value of "count" is again increamented and assigned


// to the "counter" type variable c2.

cout<<"c1= "<<c1.get_count()<<endl;
cout<<"c2= "<<c2.get_count();

getch();
}

/* NAMELESS TEMPORARY CONSTRUCTORS.

*/

//Program to show " Implementation of Postfix Notation".

#include<iostream.h>
#include<conio.h>

class counter
{
private:
unsigned int count;
public:
counter():count(0)
{
}

counter(int c): count(c) // Whenever we need to pass or return a


{ // value of the object from the class, we
} // do it only with help of single arg constructor.

unsigned int get_count()


{
return count;
}

counter operator ++()


{
return counter(++count); // increment count (prefix)
} // again an unnamed object of counter type // is
created and passed.
// us created and passed.

counter operator ++(int) // Here "int" is not any argument,it just used
{ // to indicate the compilor to create a postfix
return counter(count++); // notation for the variable "counter".
}
// an unnamed object of counter type is created
// and passed to the calling function.

};

int main()
{
clrscr();

counter c1,c2;
cout<<"c1= "<<c1.get_count()<<endl;
cout<<"c2= "<<c2.get_count()<<endl;

++c1; //the value of "count" variable is increamented by 1.

c2=++c1; // value of "count" is again increamented and assigned


// to the "counter" type variable c2.

c2=c1++; // Here the postfix incrementation is applied.

c2++; // Againg postfix incrementation.


cout<<"c1= "<<c1.get_count()<<endl;
cout<<"c2= "<<c2.get_count();

getch();
}

Overloading Binary Operators.

/* OVERLOADING BINARY OPERATORS.

BINARY OPERTORS: those operators, which operates on two inputs are called
binary operators.
example: +,-,*,/ and so on.

Binary operators can also be overloaded to perform some additional tasks,


other than which they perform by default.*/

//Programe which show "overloading of arithmetic binary operator".

#include<iostream.h>
#include<conio.h>

class distance
{
private:
int feet;
float inches;

public:
distance(): feet(0),inches(0.0)
{
}

distance(int ft,float in): feet(ft),inches(in)


{
}
void getdist()
{
cout<<"\n Enter feet:";
cin>>feet;
cout<<"\n Enter inches:";
cin>>inches; //........ Here we also can add the mechanizm
} to convert the inches to the feet.

void showdist() const // this fuction is defined as constant bcoz


{ // const objects works only with const functions.
cout<<feet<<"."<<inches<<endl;
}

distance operator +(distance) const; // protoype, becoz defined outside


}; // outside the class.

distance distance::operator +(distance d2) const // header and body of


{ // overloading function.
int f=feet+d2.feet;
float i=inches+d2.inches;
if(i>=12.0) //..................Converts the inches to feet.
{
i=12.0;
f++;
}
return distance(f,i);
}

int main()
{
distance dist1,dist3,dist4;

dist1.getdist();

distance dist2(11,6.25); // passed to overloading function.


dist3=dist1+dist2;
dist4=dist1+dist2+dist3;

cout<<"dist1="; //
dist1.showdist(); // these lines are just used to
//
cout<<"dist2="; // display the results,
dist2.showdist(); //
// stored in different objects, with help
cout<<"dist3="; //
dist3.showdist(); // of show function.
//
cout<<"dist4="; //
dist4.showdist(); //
//
return 0;
}

/* OVERLOADING ASSINGNMENT (=) OPERATOR...... BINARY OPERATOR.

+=,...... This operator combines "assignment" and "addition" operations in


in one single line.

we will use this operator to add one distance to another, means we


will overload it
*/

// += overloading programe.

#include<iostream.h>
#include<conio.h>

class distance
{
private:
int feet;
float inches;

public:

distance():feet(0),inches(0.0)
{
}

distance(int ft,float in):feet(ft),inches(in)


{
}

void getdist()
{
cout<<"Enter feet:"<<endl; cin>>feet;
cout<<"Enter inches:"<<endl; cin>>inches;
}
void showdist() const
{
cout<<feet<<"-"<<inches<<endl;
}

void operator += (distance);


};

void distance :: operator += (distance d2)


{
feet += d2.feet;
inches += d2.inches;

if(inches >= 12.0)


{
inches = inches - 12.0;
feet++;
}
}

int main()
{
distance dist1;
dist1.getdist();

cout<< "dist1: ";


dist1.showdist();

distance dist2(6,2.5);

//cout<<"dist1: " ; dist1.showdist();


cout<<"dist2: " ; dist2.showdist();

dist1 += dist2;

cout<<"after addition"<<endl<<endl;

cout<<"dist1: ";
dist1.showdist();
cout<<endl;

getch();
}

/* COMPARISON OPERATOR OVERLOADING.


=> The comparison operators like <,>,<= and >= can also be overloaded.

=> Here we are overloading the less than (<> comparison operator, and the
same process is followed for overloading all the operators.

=> this is not possible in traditional way to compare two objects with these
operators, like
dist1 < dist2
After performing the following operational code to overload the
< operator,it becomes possible.

*/

// overloading "less than (<)" operator.

#include<iostream.h>
#include<conio.h>

class distance
{
private:
int feet;
float inches;

public:

distance():feet(0),inches(0.0)
{
}

distance(int ft,float in):feet(ft),inches(in)


{
}

void getdist()
{
cout<<"Enter feet:"<<endl; cin>>feet;
cout<<"Enter inches:"<<endl; cin>>inches;
}

void showdist() const


{
cout<<feet<<"-"<<inches<<endl;
}
bool operator < (distance) const; // boolian datatype, which can store only
}; // two values, i.e "true" and "false".

bool distance::operator < (distance d2) const


{
bool ret;
float bf1= feet + inches / 12; // converts the total distance to only inches.
float bf2= d2.feet + d2.inches /12;
// return (bf1 < bf2) ? true:false; // this line meaning is same as all lines,
// coded bellow it.
if(bf1 < bf2)
ret = true;
else
ret = false;

return ret;
}

int main()
{
distance dist1;
dist1.getdist();

distance dist2(6,2.5);

cout<<"dist1: " ; dist1.showdist();


cout<<"dist2: " ; dist2.showdist();

if(dist1 < dist2)


cout<<"Dist1 is less than dist2"<<endl;
else
cout<<"dist1 is greater than dist2"<<endl;

getch();
}

/* CONCATINATING STRINGS USING OPERATOR OVERLOADING

Usualy strings cant be concatinated using the + operator. However by


overloading the + operator, we can concatinate strings with it.

str3 = str2 + str1; ........ Not valid without overloading.


where str1,2 and 3 are strings.

*/
// Concatinating Strings.

#include<iostream.h>
#include<conio.h>
#include<string.h> //..... Libraries, which contain the definition of
#include<stdlib.h> // strcpy(), strlen() functions,used in programe.

class string
{
private:
enum //.... it is an enumerated data type, which counts down the
{ // the memory loacations used in this datatype.
sz=80
};
char str[sz]; // A string of 80 characters is declared.

public:
string() // Constructor Declaration.
{
strcpy(str,"");
}

string(char s[]) // 2nd Constructor Declaration.


{
strcpy(str,s); // Builtin function, which copy the string "s" to
} // to string "str".

void display() const // A constant function, which disply the string "str".
{
cout<<str<<endl;
}

string operator + (string ss) const // overloading function, which has


{ // string type arg nemed "ss" and returns
string temp; // string value.
if(strlen(str) + strlen(ss.str)<sz)
{
strcpy(temp.str,str); // copy the string "str" to string "temp.str".

strcat(temp.str,ss.str); // Built in function for concatinating both the


} // given strings ie (temp.str and ss.str).
else
{
cout<<"\n String overflow";
exit(1);
}
return temp; // returns temp, which type is "string" to the
} // calling position.
};

void main()
{
string s1="\n Salam "; // initialization of first string.
string s2=" and Eid Mubarak"; // initialization of second string.
string s3;

s1.display();
s2.display();
//s3.display(); // S3 is empty string, becoz nothing is assigned to it till now.

s3=s1+s2; // valid, because of overloading function.

s3.display(); // s3 is not empty, s1 and s2 are concatinated and assigned


cout<<endl; // to the string "s3".
//return 0;
getch();
}

You might also like