Hello to all !
i am encoding a class about rational numbers, holding the numerator and a denominator and all operators like are overloaded for it..it works all so fine ecxept for one wierd point:

my cast-to-double operator is called at the times it is not called at all..for example i debugged the program and noticed that it is called in the copy constructor, while i never used the function in it..i donno what i'm doing wrong? what is it that puts the compiler into the mistake of calling this function at times it is not called?

class Rational
	int numerator;
	int denominator;
	Rational(Rational &r);
	Rational(int n=1,int d=1);
	Rational operator+(Rational num);
	Rational operator-(Rational num);
	Rational operator*(Rational num);
	Rational operator/(Rational num);
	Rational& operator++();
	Rational operator++(int a);
	Rational& operator--();
	Rational operator--(int a);
	int getnumerator();
	int getdenominator();
	void setnumerator(int n);
	void setdenominator(int d);
	[B]operator double() const  
		return numerator/(double)denominator;
	operator string();

for example it is called in the line bolded below :

Rational& Rational::operator --()
	Rational one(-1,1);
	[B]Rational result(*this+one);[/B]
	[B]return *this;[/B]

can any one figure out why ? :-?
tanx in advance

Recommended Answers

All 4 Replies

Please post the code for the constructor - you have posted only declaration, no definitions, so we can't see what is going on!

Member Avatar
operator double() const  
		return numerator/(double)denominator;
	operator string();

no return types???

In C++, the copy constructor is supposed to take a const reference to self (const Rational&)

You declared only non-const construction from Rational. Hence, the compiler is forced to select conversion to double (which is const) followed by construction from int (after demoting double to int.) It cannot use your non-const copy constructor, since the temporary (*this + one) is const, as all temporaries are.

Since your test case uses the boundary case of denominator equals 1, the error is not detected, even though you are actually losing precision when the double is demoted to int.

1) make your copy constructor Rational(const Rational& rRight)

2) choose test cases that use more of your code, like non-integer rationals

You pointed out the bug quite well , dear mr.ammo !... Thank you very much for your contribution.

Be a part of the DaniWeb community

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