I was writing a program for adding 2 objects of a class.
//program for adding 2 objects data of same class
#include<iostream>
using namespace std;
class distances
{
private:
int feet;
float inches;
public:
distances() //constructor
{
feet = 0;
inches = 0.0;
}
distances(int f, float i) //constructor
{
feet = f;
inches = i;
}
void get_data() //taking value
{
cout << "Enter the distance in feet and inches :: " << "\n";
cin >> feet >> inches;
}
void show_data() //showing data
{
cout << "The distance in feet is ::" << feet
<< " and in inches is :: " << inches;
}
void add(distances d1, distances d2); //adding to objects
};
void distances::add(distances d1, distances d2)
{
inches = d1.inches + d2.inches;
feet = 0;
while(inches >= 12)
{
inches = inches - 12;
++feet;
}
feet += d1.feet + d2.feet;
}
void main()
{
distances d1, d2, d3;
d1.get_data();
d2.get_data();
d3.add(d1, d2);
d3.show_data();
getch();
}
My program worked fine but my sir told that my approach of adding 2 objects was wrong ,although he didn't tell why.He told me that my approach won't work when I will add more objects. I don't know why my approach was wrong.My friend told me that my problem might be in the line d3.add(d1,d2);
Is that true?
My second problem was that when I used class name,function name and constructor name as distance instead of distances then following error was coming
1>c:\users\abc\documents\visual studio 2010\projects\pass\pass\pass.cpp(47): error C2872: 'distance' : ambiguous symbol
1> could be 'c:\users\abc\documents\visual studio 2010\projects\pass\pass\pass.cpp(6) : distance'
1> or 'c:\program files (x86)\microsoft visual studio 10.0\vc\include\xutility(899) : iterator_traits<_Iter>::difference_type std::distance(_InIt,_InIt)'