Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Special Interest Groups
  3. C++ Gurus
  4. Both const and non-const getter - compiler picks the wrong one?
Qt 6.11 is out! See what's new in the release blog

Both const and non-const getter - compiler picks the wrong one?

Scheduled Pinned Locked Moved C++ Gurus
2 Posts 1 Posters 2.0k Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A Offline
    A Offline
    Asperamanca
    wrote on last edited by
    #1

    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?

    1 Reply Last reply
    0
    • A Offline
      A Offline
      Asperamanca
      wrote on last edited by
      #2

      My fault. Clearly, "other" is const in contextData(), therefore a const reference is returned.

      1 Reply Last reply
      0

      • Login

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • Users
      • Groups
      • Search
      • Get Qt Extensions
      • Unsolved