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++

Description

Reports a virtual operator== or operator< member declaration or definition.

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;
};

Remediation

Declare the comparison as a non-virtual member or a free function, and use dynamic_cast (or a dedicated virtual equals/compare method with an explicit contract) inside its body if polymorphic comparison is genuinely required.

Configuration

This detector does not need any configuration.

© 2026 Xygeni. All rights reserved