Mar 16, 2011

C++ Error: Discards Qualifiers

What the compiler actually said:

passing 'const MyNamespace::MyClass as 'this' argument of 'const SomeReturnClass& MyNamespace::MyClass::GetEntryRect()' discards qualifiers.

What the compiler meant to say:

You failed to promise me that MyClass::GetEntryRect  won't modify the state of MyClass in any way. That is, you failed to add the const qualifier to the end of the class name.

An Example

For example,  MyNewClass constructor gets a const reference to NumericUpDown and uses it to initialize m_myParentsRectangle to the rectangle contained in NumericUpDown.

MyNewClass::MyNewClass(const NumericUpDown& parentControl)
: m_myParentsRectangle(parentControl.GetEntryRectangle() )

This generates the following compiler error (namespaces elided for brevity):

passing 'const NumericUpDown' as 'this' argument of 'const Rectangle& NumericUpDown::GetEntryRect()' discards qualifiers

A quick look at NumericUpDown.h shows

const Rectangle& GetEntryRect() ;

Seems OK, it's returning a const reference so nothing in the NumericUpDown class is getting changed, yet the constructor thinks it's throwing away the constness of parentControl.

Making the compiler happy

The compiler just needs to be promised that GetEntryRect() does not intend to modify anything in its containing class. It's not enough that its contained rectangle is returned as const, it's possible that GetEntryRectangle() could be doing something else to change the state of its containing class. It pledges to do no such thing by appending const to the end:

const Rectangle& GetEntryRect() const;

Of course you need to add the const in both the .h file and the .cpp or you'll get a

prototype for 'void Rectangle::GetEntryRect() const' does not match any in class

About Me

My photo
Tod Gentille (@todgentille) is now a Curriculum Director for Pluralsight. He's been programming professionally since well before you were born and was a software consultant for most of his career. He's also a father, husband, drummer, and windsurfer. He wants to be a guitar player but he just hasn't got the chops for it.