Both const and non-const getter - compiler picks the wrong one?
-
I have an assignment operator like this:
@CTcm_AbstractTextEntry& CTcm_AbstractTextEntry::operator =(const CTcm_AbstractTextEntry& other)
{
if (&other == this)
{
return *this;
}// Intentional swallow copy m_pContextData = &other.contextData(); return *this;
}@
m_pContextData is a private member:
@
private:
CTcm_ContextDataObject* m_pContextData;@I have implemented the getter contextData() both const and non-const, like I've often seen in Qt:
@CTcm_ContextDataObject& CTcm_AbstractTextEntry::contextData()
{
if ( ! m_pContextData)
{
CTcm_Methods::unexpectedErrorFatalExit("m_pContextData is Null", FILE, LINE);
}return *m_pContextData;
}
const CTcm_ContextDataObject& CTcm_AbstractTextEntry::contextData() const
{
if ( ! m_pContextData)
{
CTcm_Methods::unexpectedErrorFatalExit("m_pContextData is Null", FILE, LINE);
}return *m_pContextData;
}@
Now the compiler tells me:
bq. error: invalid conversion from 'const CTcm_ContextDataObject*' to 'CTcm_ContextDataObject*'Why doesn't the compiler pick the non-const variant, since the assignment operator clearly isn't a const member function?
-
My fault. Clearly, "other" is const in contextData(), therefore a const reference is returned.