December 3rd, 2012, 09:41 PM
Help this program
obj:- Funtion returning object and passing object as function
i create but some erorr
Distance(int f,int i)
Distance addDistance(Distance d1,Distance d2)
cout<<"Enter Distance 1 feets: ";
cout<<"Enter Distance 2 inches: ";
December 3rd, 2012, 11:53 PM
Originally Posted by Mansoor54
this line contains the error , u see, as addDistance() is a member function of class Distance hence it can be accessed only by variable/object (like d3) of that class using dot(.) operator and not indipendently. so the correct statement is
December 4th, 2012, 09:26 PM
December 5th, 2012, 10:44 AM
There is some semantically very suspect code in this:
Will instantiate a Distance object representing 2 feet and two inches. Is that really what you intended!?
Will create a Distance object for 2 feet 13 inches, not 3 feet 1 inch.
Distance x = addDistance(Distance( 1, 6 ), Distance( 1, 7))
Will create a Distance object for 1 feet 14 inches; it would make sense to normalise it to 2 feet 2 inches.
The whole thing can be simplified if you store all distances internally in inches (although this is the 21st Century millimetres might be better). So for example:
The member function addDistance() can be declared static to overcome your original problem. It is more normal to have a non-static member that just takes a single operand and adds it to the object for which it was called:
Distance( int i )
inches = i ;
Distance( int f, int i )
inches = f * 12 + i ;
cout << "\nFeet = " << inches / 12 ;
cout << "\nInches = " << inches % 12;
static Distance addDistance(const Distance& d1, const& Distance d2)
return Distance( d1.inches + d2.inches ) ;
And this is an obvious opportunity to operator overloading:
Distance& addDistance(const Distance& d )
inches += d ;
return *this ;
Also "Feet" is the plural of "Foot", "Feets" is just not English.