Why does using const with class declaration generate error C2662?



This is from Ivor Horton's C++ book (2013) chapter 7.

Here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#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)
	{
		return this->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?
What compiler do you use? I'm using GCC 4.9.2 works fine for me.
Ignore me. I forgot to "declare the cigar as a const".
Last edited on
Hi,

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.

28
29
30
31
bool compare(const CBox& xBox) const
	{
		return this->volume() > xBox.volume();
	}


This is saying that we will not alter the argument, nor the state of the object (none of it members are altered)

C++ is very strict about it's types and this is one of it's strengths.
Topic archived. No new replies allowed.