Comparison operator declared virtual
ID |
c.maintainability.virtual_comparison_operator |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
medium |
Remediation Effort |
medium |
Resource |
Design |
Language |
C / C++ |
Rationale
Comparison operators take their arguments by value or reference, not by pointer, so calling a == b never goes through a vtable lookup on b — only the type of a participates in overload resolution, and the comparison is resolved statically at the call site regardless of `b’s dynamic type. Making the operator virtual is therefore misleading: it suggests polymorphic comparison behavior that C++ overload resolution does not provide, and invites a derived class to override it with an asymmetric or type-unsafe implementation.
The following code illustrates the pattern detected by this rule:
class Base {
public:
// FLAGGED: Comparison operator declared virtual
virtual bool operator==(const Base &other) const;
};