Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-5817

Member functions that don't mutate their objects should be declared "const"

    XMLWordPrintable

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way, MISRA C++ 2008 recommended
    • Covered Languages:
      C++
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      5min
    • Analysis Scope:
      Main Sources, Test Sources

      Description

      No member function can be invoked on a const-qualified object unless the member function is declared "const".

      Qualifying member functions that don't mutate their object with the "const" qualifier makes your interface easier to understand; you can deduce without diving into implementation if a member function is going to mutate its object.

      Also, const-qualified member functions make working with const-qualified objects possible. The compiler ensures that only member functions that are declared "const" can be invoked on "const" objects. Avoiding declaring non-mutating member functions const might break const-correctness: it will not be possible to invoke such non-mutating functions on const-qualified objects.

      Noncompliant Code Example

      class A {
        void f(){ // Noncompliant
          std::cout<< "f doesn't mutate A";
        }
      };
      

      Compliant Solution

      class A {
        void f() const {
          std::cout<< "f doesn't mutate A";
        }
      };
      

      Exceptions

      Virtual member functions that don't mutate their objects don't necessarily need to be declared const. This might be done in order to allow them to be overridden by non-const functions.

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              geoffray.adde Geoffray Adde
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Created:
                Updated: