#include <iostream>
using std::cout;
using std::endl;
class CBox // Class definition at global scope
{
private:
double m_Length; // Length of a box in inches
double m_Width; // Width of a box in inches
double m_Height; // Height of a box in inches
public:
// Constructor definition
explicit CBox(double lv = 1.0, double wv = 1.0, double hv = 1.0) : m_Length {lv}, m_Width {wv}, m_Height {hv}
{
cout << "Constructor called." << endl;
}
// Function to calculate the volume of a box
double volume()
{
return m_Length*m_Width*m_Height;
}
// Function to compare two boxes which returns true
// if the first is greater than the second, and false otherwise
bool compare(CBox& xBox)
{
returnthis->volume() > xBox.volume();
}
};
int main()
{
CBox match {2.2, 1.1, 0.5}; // Define match box
CBox cigar {8.0, 5.0, 1.0}; // Define cigar box
if(cigar.compare(match))
cout << "match is smaller than cigar" << endl;
else
cout << "match is equal to or larger than cigar" << endl;
return 0;
}
The idea is that when we declare the cigar as a const with initialization list i.e 'const CBox cigar {8.0, 5.0, 1.0}', and then call call the compare function as shown above, we get the following error message:
1 2
error C2662: 'CBox::compare' : cannot convert 'this' pointer
from 'const CBox' to 'CBox &' Conversion loses qualifiers
My confusion is that since the compare function does not change anything in the class CBox:
(1) Why does the program need to convert the 'this' pointer and convert it to what?
(2) The 'this' pointer can only have 1 value in lifetime of an object. Why then does this generate error?
(3) What does the second error mean?
I ran your code using cpp.sh (the gear icon top right of the code) with all 3 warning levls turned on, and with const on line 37.
In function 'int main()':
40:24: error: no matching function for call to 'CBox::compare(const CBox&)'
40:24: note: candidate is: 28:7: note: bool CBox::compare(CBox&)
28:7: note: no known conversion for argument 1 from 'const CBox' to 'CBox&'
To me that is straight forward there is no such function with const in it.
By the way, both of your functions should have const parameters and be marked const as well.