Compile time polymorphism using operator overloading
Create a class Distance with feet and inches. Write an overloaded function to copy the value of one distance object into another distance object using = operator overloading.
#include <iostream>
using namespace std;
class Distance
{
int _feet;
float _inches;
public:
int GetFeet()
{
return _feet;
}
float GetInches()
{
return _inches;
}
void SetFeet(int feet)
{
_feet = feet;
}
void SetInches(float inches)
{
_inches = inches;
}
Distance()
{
_feet = 0;
_inches = 0;
}
Distance(int feet, float inches)
{
_feet = feet;
_inches = inches;
}
Distance(const Distance &distance)
{
_feet = distance._feet;
_inches = distance._inches;
}
Distance& operator=(Distance &distance)
{
_feet = distance.GetFeet();
_inches = distance.GetInches();
return *this;
}
};
int main()
{
Distance d1, d2;
cout << "Before assigning: feet = " << d2.GetFeet() << ", inches = " << d2.GetInches() << endl;
d1.SetFeet(10);
d1.SetInches(20.0);
d2 = d1;
cout << "After assigning: feet = " << d2.GetFeet() << ", inches = " << d2.GetInches() << endl;
return 0;
}
Comments
Leave a comment