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

Comparison operators should not be virtual

    XMLWordPrintable

    Details

    • Message:
      Remove this "virtual" specifier and refactor the code to not require polymorphism for comparison operators.
    • Highlighting:
      Hide

      virtual keyword

      Show
      virtual keyword
    • Default Severity:
      Blocker
    • Impact:
      High
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way, MISRA C++ 2008 recommended
    • Covered Languages:
      C++
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      1h
    • Analysis Scope:
      Main Sources, Test Sources
    • CppCoreGuidelines:
      C.87

      Description

      Making a comparison operator virtual implies that you want to compare objects of different types by overriding operator==, for instance, in a subclass to compare instances of the base class with instances of the subclass. But polymorphic comparison operators are very difficult to get right, and are actually questionable in concept. After all, can two objects with only a few common members really be equal?

      This rule raises issues on virtual comparison operators.

      Noncompliant Code Example

      struct Foo {
        virtual bool operator==(const Foo &other) const; // Noncompliant
        virtual bool operator!=(const Foo &other) const; // Noncompliant
      };
      

      Compliant Solution

      struct Foo {
        bool operator==(const Foo &other) const;
        bool operator!=(const Foo &other) const;
      };
      

      See

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              alban.auzeill Alban Auzeill
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Created:
                Updated: