The code below is part of the Distance class. The operator overload is a friend function declared as a private member of the Distance class and the function I try to call is a public member. This function does not change member variables of the Distance class.
I'm trying to keep the two call-by-reference objects d1 and d2 constant, but my compiler says I violate their const property by calling the ConvertToInches function, or any function located inside the distance class, despite these functions not changing private variables within the Distance class.
The compiler does not have a problem when I do not make d1 and d2 constant.
Could anyone explain how to make d1 and d2 constant while calling this function and why what I have does not work?
Thanks!
const Distance operator+(const Distance& d1, const Distance d2)
//this is a friend function
//declared in private section of Distance class
{
//this function is what causes problems !!!!!!!
d1.ConvertToInches(1, 2, 3, 4);
Distance d3 = 3;
return d3;
}
Distance::ConvertToInches(const int cMiles, const int cYards, const int cFeet, const int cInches)
//declared in public section of Distance class
{
cMiles = cMiles * 63360;
cYards = cYards *36;
cFeet = cFeet * 12;
int cSum = cMiles + cYards + cFeet + cInches;
return cSum;
}
The problem is that the ConvertToInches method is not declared const, and you're attempting to call methods on a const Distance& object. A simple fix is to add const to the declaration and the definition of the function:
class Distance
{
public:
int ConvertToInches(const int cMiles, const int cYards, const int cFeet, const int cInches) const;
};
int Distance::ConvertToInches(const int cMiles, const int cYards, const int cFeet, const int cInches) const { /* ... */ }
One other minor problem with your code snippet: d2 is not a const reference like d1.