C++ provides the facility of not only overloading the functions but also the facility of overloading operators like +,- etc. Normally these operators works only with inbuilt data types eg: int , float , double etc and can not work on user defined data types like Distance which is the combination of two types of data members like feet and inch, like Date which have three types of data members eg: Day, Month and Year or Time which have hours, mins and sec. or Complex number which is the combination of real and imaginary numbers. So we improve the programs by overloading the existing operators to work on user defined data types. Operators like . , :: and .* can not be overloaded.

Note : Java does not support Operator Overloading and also the Pointers .

Example program in C++ to Overload the existing + Operator to work with user defined data type distance. You can also try to overload -, * and / operators to work with the distance type.

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

class distance //Defining Class distance
{

private:
int feet,inch; // private int data type members feet and inch

public:
distance(){} //Constructor

void getDist() //Function to read distance.
{

cout<<" Feet : ";
cin>>feet;
cout<<" Inch : " ;
cin>>inch;


}

void showDist() //Function to Show the distance

{
cout<<feet<<" Feet " <<inch <<" Inch "<<endl;
}


distance operator + (distance d1) //Overloading existing + operator to type distance
{
distance d3; //declaring object d3 store the result
d3.feet=feet+d1.feet; //adding feet to the feet of object d1 and assigning result into feet of object d3
d3.inch=inch+d1.inch; //adding inch to the inch of object d1 and assigning result into inch of object d3


if(d3.inch>=12) //Checking if inch of d3 is greater than or equal to 12
{
d3.feet++; //if yes increase feet of d3 by 1
d3.inch-=12; //and decrease the inch of d3 by 12
}

return d3; //return the object d3 which contains result of addition

}






};

int main()
{

distance d1,d2,d3; //Declaring objects d1,d2,d3 of type distance

cout<<"Enter the Distance in Feet and Inches for d1: " <<endl;
d1.getDist(); //calling getDist function to read feet and inch into object d1

cout<<"Enter the Distance in Feet and Inches for d2: " <<endl;
d2.getDist(); ///calling getDist function to read feet and inch into object d2

d3=d1+d2; //now using overloaded + operator to add objects d1 and d2


cout<<"Result : "<<endl;


d3.showDist(); //Displaying result which was assing to object d3


getch();

return(0);
}

Note : Adjust the comments section according to your IDE or Editor.

0 comments:

Post a Comment

 
Top