Member Avatar for Member #897610
/*i want to overloaded operator in my program. but i dnt know how to add overloaded + operator in this prgram. plzzzzzzzzz help me to solve this problem*/ 
#include<iostream.h>

class rational{
private :

int numerator, dnomenator ;
void reduction();

public :
rational ()          //default contructer
{
numerator=dnomenator=1;
}
rational (int num, int dnum)   //parameterised constructer
 {
	  numerator=num;dnomenator=dnum;
	  reduction();
 }
 void show();
 rational operator +();
};
rational rational ::operator +(){

 rational sum;
 sum=numerator+dnomenator;
return sum;
}
void rational ::show(){
cout<<numerator<<"/"<<dnomenator<<endl;
}


void rational::reduction()//reduces the fraction
 {
 int largest;
 largest = numerator > dnomenator ? numerator : dnomenator;
  /*if(numerator>dnomenator)
		{
		largest=dnomenator;
		}
		else
		{
		largest=numerator;
		}*/
 int gcd = 0; // greatest common divisor

for ( int count= 2; count <= largest; count++ )
 if ( numerator % count == 0 && dnomenator % count == 0 )
 gcd = count;

 if (gcd != 0)
 {
 numerator /= gcd;
 dnomenator /= gcd;
 }
 }


int main()
{
rational r;
rational c(4,6);
c.show();
return 0;
}

Dani AI

Generated

This thread shows the common pitfalls when implementing arithmetic for a Rational type: constructing the result object without initializing its fields, performing I/O inside operator implementations, using nonstandard headers (like <iostream.h> and <conio.h>), and declaring comparison operators with the wrong return type. ’s suggestion to provide stream operators is useful; ’s idea of matching denominators is on the right track but can be implemented more cleanly and efficiently with a gcd-based reduction.

Correct signatures to keep in mind:

  • As a member: Rational operator+(const Rational& rhs) const; — left operand is *this.
  • As a non-member/friend: friend Rational operator+(const Rational& lhs, const Rational& rhs); — both operands are parameters.
    Pass operands by const&, return a new reduced Rational by value, and do not do printing inside operators.

A minimal, portable pattern (original example) — constructor normalizes, operator+ builds the cross-multiplied numerator/denominator and reuses normalization:

#include <iostream>
#include <stdexcept>

class Rational {
    long long n_, d_;
    static long long gcd(long long a, long long b){
        if (a<0) a=-a; if (b<0) b=-b;
        while (b){ long long t=a%b; a=b; b=t; }
        return a? a:1;
    }
    void normalize(){
        if (d_==0) throw std::invalid_argument("zero denominator");
        if (d_<0){ n_ = -n_; d_ = -d_; }
        long long g = gcd(n_, d_);
        n_/=g; d_/=g;
    }
public:
    Rational(long long n=0, long long d=1): n_(n), d_(d){ normalize(); }
    Rational operator+(const Rational& rhs) const {
        long long n = n_*rhs.d_ + rhs.n_*d_;
        long long d = d_*rhs.d_;
        return Rational(n, d);
    }
    friend std::ostream& operator<<(std::ostream& os, const Rational& r){
        return os << r.n_ << '/' << r.d_;
    }
};

Notes and troubleshooting:

  • Do not print inside operators; let operator<< handle output.
  • Use normalize() (or std::gcd in C++17+) to reduce results.
  • operator== and operator> should return bool, not Rational.
  • Watch integer overflow (use wider integer type or detect overflow) and always guard against zero denominators (throw or handle). This approach will make expressions like R(3,2) + R(9,4) produce the expected 15/4.

Recommended Answers

All 10 Replies

To add overloading operators to a class definition, you need to add them as a FRIEND function.

friend <type_name> operator <operator>(const <type_name>& var1, const <type_name>& var2)

// Example - rational is a class name not shown but defined else where
friend rational operator+(const rational& var1, const rational& var2){
<some code>
}

Would be how you would define a friend operator function. The difference between a friend function and an ordinary function that are defined in a class, the friend function is not a calling function from any one particular object but may be used for one or more objects (unary operation, binary operation)


Once you figure out how to overload the + operator, you can overload the << operator instead of using the show() function.

friend ostream& operator << (ostream& outs, const rational& object);
//Precondition. If outs is a file, outfile has been opened.
// Object have been given a value. Will output object members to outs ostream
}

...........

commented: what is this..????/ +0
Member Avatar for Member #897610
/*overload +operator in my program it  plz cheak this & thisi will be thnkfull if u help me*/
#include<iostream.h>

class rational{
private :

int numerator, dnomenator ;
void reduction();

public :
rational ()          //default contructer
{
numerator=dnomenator=1;
}
rational (int num, int dnum)   //parameterised constructer
 {
	  numerator=num;dnomenator=dnum;
	  reduction();
 }
 void show();
 rational operator +(rational r );
};
rational rational ::operator +(rational r){


rational sum;
sum.numerator =numerator*sum.numerator;
sum.dnomenator=dnomenator*sum.dnomenator;
cout<<"The sum after multplication is  :"<<endl;
return sum;

}
void rational ::show(){
cout<<"The least reduce fraction is : "<<numerator<<"/"<<dnomenator<<endl<<endl;
}
void rational::reduction()//reduces the fraction
 {
 int largest;
 largest = numerator > dnomenator ? numerator : dnomenator;
 int gcd = 0; // greatest common divisor

for ( int count= 2; count <= largest; count++ )
 if ( numerator % count == 0 && dnomenator % count == 0 )
 gcd = count;

 if (gcd != 0)
 {
 numerator /= gcd;
 dnomenator /= gcd;
 }
 }


int main()
{
int numerator,denomenator,num,denom;
rational c;
c.show();
cout<<"Enter the nomirator :";
cin>>num;
cout<<"Enter the denominator : ";
cin>>denom;
rational c1(num,denom);
c1.show();
cout<<"Enter the nomirator :";
cin>>numerator;
cout<<"Enter the denominator : ";
cin>>denomenator;
rational c2(numerator,denomenator);
c2.show();
rational c3;
c3=c1+c2;
c3.show();
return 0;
}

Please reread what I wrote, then check your answer with mine. Do they look similar? Do they have the same amount of parameters? You also declined to add the friend function declaration in the class definition, without it, the class will not know where to look for the + operator.

Here is a quick tutorial that should help with your needs.

http://www.cplusplus.com/doc/tutorial/classes2/

Member Avatar for Member #897610

/*there is little difference b/w your and mine program your program take two value sum up them my program is little difference.1st i take two fraction ,e.g 6/4,9,15

first my program reduce these fraction e.g 6/4 into 3/2 ,9/4 into 3/5 then
add them eg
3/2+9/4
the answer must be 15/4 but my program provide wrong answer. what was wrong with it.... i can't understand the logic of the program.*/

#include<iostream.h>
#include<conio.h>
class rational{
private :

int numerator, dnomenator ;
void reduction();

public :
rational ()          //default contructer
{
numerator=dnomenator=1;
}
rational (int num, int dnum)   //parameterised constructer
 {
	  numerator=num;dnomenator=dnum;
	  reduction();
 }
 void show();
 rational operator +(rational r );
};
rational rational ::operator +(rational r){


rational sum;
sum.numerator =numerator+sum.numerator;
sum.dnomenator=dnomenator+sum.dnomenator;
cout<<"The sum afer adeng both fraction  is  :"<<endl;
return sum;

}
void rational ::show(){
cout<<"The least reduce fraction is : "<<numerator<<"/"<<dnomenator<<endl<<endl;
}
void rational::reduction()//reduces the fraction
 {
 int largest;
 largest = numerator > dnomenator ? numerator : dnomenator;
 int gcd = 0; // greatest common divisor

for ( int count= 2; count <= largest; count++ )
 if ( numerator % count == 0 && dnomenator % count == 0 )
 gcd = count;

 if (gcd != 0)
 {
 numerator /= gcd;
 dnomenator /= gcd;
 }
 }


int main()
{
int numerator,denomenator,num,denom;
rational c;
c.show();
cout<<"Enter the nomirator :";
cin>>num;
cout<<"Enter the denominator : ";
cin>>denom;
rational c1(num,denom);
c1.show();
cout<<"Enter the nomirator :";
cin>>numerator;
cout<<"Enter the denominator : ";
cin>>denomenator;
rational c2(numerator,denomenator);
c2.show();
rational c3;
c3=c1+c2;
c3.show();
return 0;
}
rational operator+(rational d)//where num and den are numerator and denominater                        
{
    int k,n;
    rational f;
    k=den*d.den;
    for(int i=1;i<=k;i++)
    {
        if(i%den==0 && i%d.den==0)
        {
            n=i;
            break;
        }
        else
        {
            n=k;
        }
    }
    f.num=(n/den)*num+(n/d.den)*d.num;
    f.den=n;
    return (f);
}

I think I helped

rational operator+(rational d)//where num and den are numerator and denominater                        
{
    int k,n;
    rational f;
    k=den*d.den;
    for(int i=1;i<=k;i++)
    {
        if(i%den==0 && i%d.den==0)
        {
            n=i;
            break;
        }
        else
        {
            n=k;
        }
    }
    f.num=(n/den)*num+(n/d.den)*d.num;
    f.den=n;
    return (f);
}

I think I helped

// Example - rational is a class name not shown but defined else wherefriend rational operator+(const rational& var1, const rational& var2){<some code>}

What I wrote above is wrong with this set up. It is correct that the + operator only takes one argument, not two. The first argument is actually the variable on the left side of the + sign in the equation between the two objects. The second variable is the one that is passed which is on the right side of the object.

A + B // A is the first argument, B is the second which is passed to the function.

The reason why you want to overload an operator to a class is due to the unknown variables you actually want to add. You will specify which variables to be combined into a -new- object, the returned object.

// class
class stuff{
public:

  <some other functions declared>

   // declared friend operator 
   friend stuff operator +(const rational& obj);

private:
   int var1;
   int var2;
};
// declared function

stuff stuff::operator +(const rational& obj){
   stuff temp;    // will create a new object of type stuff to store the sum

   // we will add the two objects together with the desired variables and 
   // save them in the new temp object.

   temp.var1 = var1 + obj.var1;
   // in the example of A + B, var1 is referenced to A, 
   // and obj.var1 is referenced to B.

   temp.var2 = var2 + obj.var2;
   // in the example of A + B, var2 is referenced to A, 
   // and obj.var2 is referenced to B.
  
   // now to return the new object with the saved results of both A + B
   return temp;
}
rational rational ::operator +(rational r){


rational sum;
sum.numerator =numerator+sum.numerator;
sum.dnomenator=dnomenator+sum.dnomenator;
cout<<"The sum afer adeng both fraction  is  :"<<endl;
return sum;

}

Few things wrong with the logic of this.
1. You need to add two separate objects together, not one object and the sum of two objects.

Ex.
You want A + B = C
not A + C = C

This is shown with both additions in the previous code.

2. You need to find a common denominator between both fractions. If they are already equal, then you can just add the numerator and KEEP THE SAME denominator. If both denominators are different, you need to find a common denominator, then change the numerators respectively prior to adding the numerators.

Finally, you can use your reduction function to simply your answer.

Member Avatar for Member #897610

cheak frndzzz

//safwan hashmi
//safwanhashmi_04@yahoo.com
//03-04-2011
//rational.cpp

#include<iostream.h>
#include<conio.h>
class rational{
private :

int numerator, dnomenator ;
void reduction();

public :
rational ()          //default contructer
{
numerator=dnomenator=1;
}
rational (int num, int dnum)   //parameterised constructer
 {
	  numerator=num;dnomenator=dnum;
	  reduction();
 }
 void show(){
 cout<<"The reduce least frction is : "<<numerator<<"/"<<dnomenator<<endl;
 }
 rational operator *(rational r) ;
 rational operator -(rational r) ;
 rational operator +(rational r) ;
 rational operator /(rational r) ;
 rational operator >(rational r) ;
 rational operator ==(rational r) ;
friend ostream & operator<<(ostream& os,rational r)
{
os<<"("<<r.numerator<<"/"<<r.dnomenator<<")";
return os;
}
friend istream & operator>>(istream& is,rational& r)
{
is>>r.numerator>>r.dnomenator;

return is;
}

  };

rational rational ::operator *(rational r){
rational multi;
multi.numerator =numerator*r.numerator;
multi.dnomenator=dnomenator*r.dnomenator;
cout<<"\n\nRational no. after multplication";
cout<<"\nFraction after Multiplication is : "<<multi.numerator<<"/"<<multi.dnomenator;
cout<<endl;
}
rational rational ::operator -(rational r)  {
rational subtrct;
subtrct.numerator=(numerator*r.dnomenator)-(r.numerator*dnomenator);
subtrct.dnomenator=(dnomenator*r.dnomenator);
cout<<"\n\nRational no. after subtraction";
cout<<"\nFraction after subtruction is : "<<subtrct.numerator<<"/"<<subtrct.dnomenator;
cout<<endl;
}
rational rational ::operator +(rational r)  {
rational subtrct;
subtrct.numerator=(numerator*r.dnomenator)+(r.numerator*dnomenator);
subtrct.dnomenator=(dnomenator*r.dnomenator);
cout<<"\nRational no. after Addition";
cout<<"\nFraction after Addition is : "<<subtrct.numerator<<"/"<<subtrct.dnomenator;
cout<<endl;
}
rational rational ::operator /(rational r)  {
	 rational dvd;
	 dvd.numerator= numerator*r.dnomenator;
	 dvd.dnomenator=r.numerator*dnomenator;
	 cout<<"\nRational no. after dividation";
	 cout <<"\nNumenator ="<<dvd.numerator<<"\nDenominator ="<<dvd.dnomenator;
}
rational rational ::operator >(rational r){
rational lsthn;
lsthn.numerator =numerator>r.numerator;
lsthn.dnomenator=dnomenator>r.dnomenator;
if(numerator>r.numerator && dnomenator>r.dnomenator){
cout<<"\n Fraction "<<numerator<<"/"<<dnomenator<<" > "<<r.numerator<<"/"<<r.dnomenator;
}
else{cout<<"\n Fraction "<<r.numerator<<"/"<<r.dnomenator<<" > "<<numerator<<"/"<<dnomenator;}
}
rational rational ::operator ==(rational r){
rational equalequal;
equalequal.numerator =numerator==r.numerator;
equalequal.dnomenator=dnomenator==r.dnomenator;
if(numerator==r.numerator && dnomenator==r.dnomenator ){cout<<"Both the fractions equAL"<<endl;}
else{cout<<"\nFractions not equal"<<endl;}
}
void rational::reduction()//reduces the fraction
 {
 int largest;
 largest = numerator > dnomenator ? numerator : dnomenator;
 int gcd = 0; // greatest common divisor

for ( int count= 2; count <= largest; count++ )
 if ( numerator % count == 0 && dnomenator % count == 0 )
 gcd = count;

 if (gcd != 0)
 {
 numerator /= gcd;
 dnomenator /= gcd;
 }
 }


int main()
{ char ch;
do{
int numerator,denomenator,num,denom;
rational c;
cout<<"Enter the nomirator :";
cin>>num;
cout<<"Enter the denominator : ";
cin>>denom;
rational c1(num,denom);
c1.show();
cout<<"\nEnter the nomirator :";
cin>>numerator;
cout<<"\nEnter the denominator : ";
cin>>denomenator;
rational c2(numerator,denomenator);
c2.show();
int n;
rational c3;
cout<<"\nEnter your choice (option i.e 1 --> *xcation) : ";
cout<<"\nEnter your choice (option i.e 2 --> -subtrction) : ";
cout<<"\nEnter your choice (option i.e 3 --> +ddition) : ";
cout<<"\nEnter your choice (option i.e 4 --> /Divdation) : ";
cout<<"\nEnter your choice (option i.e 5 --> >gratrthn) : ";
cout<<"\nEnter your choice (option i.e 6 --> ==equalequal) : ";
cout<<"\nEnter your choice (option i.e 7 --> for sream insertion)functionalty : ";
cout<<"\nEnter your choice (option i.e 8 --> for stream extraction)functionalty : ";
cout<<"\nChose any option from a givn instruction obove :";

		 cin>>n;
		 switch(n)
		 {
			 case 1:
			 c3=c1*c2;
			 getch();
			 clrscr();
			 break;
			 case 2:
			 c3=c1-c2;
			 getch();
			 clrscr();
			 break;
			 case 3:
			 c3=c1+c2;
			 getch();
			 clrscr();
			 break ;
			 case 4:
			 c3=c1/c2;
			 getch();
			 clrscr();
			 break;
			 case 5:
			 c3=c1>c2;
			 getch();
			 clrscr();
			 break;
			 case 6:
			 c3=c1==c2;
			 getch();
			 clrscr();
			 break;
			 case 7:
			 cout<<c2;
			 getch();
			 clrscr();
			 break;
			 case 8:
			 cout<<"\nEnter the nomenator & denominator :";
			 cin>>c2;
			 cout<<c2;
			 c3=c1==c2;
			 c3=c1>c2;
			 c3=c1/c2;
			 c3=c1+c2;
			 c3=c1-c2;
			 c3=c1*c2;
			 getch();
			 clrscr();
			 break;

		 }

cout<<"Press any key to contnue or N  key to discontnue :--";
getche();
cout<<endl<<endl;
//clrscr();
}while(ch!='n' || ch!='N') ;
return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.