Details
-
Type:
Code Smell Detection
-
Status: Active
-
Resolution: Unresolved
-
Labels:
-
Message:Remove this "virtual" specifier and refactor the code to not require polymorphism for comparison operators.
-
Highlighting:
-
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
- C++ Core Guidelines C.87 - Beware of == on base classes