This rule is part of MISRA C++:2023.
Usage of this content is governed by Sonar’s terms and conditions. Redistribution is
prohibited.
Rule 13.3.2 - Parameters in an overriding virtual function shall not specify different default arguments
Category: Required
Analysis: Decidable,Single Translation Unit
Amplification
Each parameter in an overriding virtual function shall either:
- Not specify a default argument; or
- Use a constant expression as its default argument, with the corresponding parameter in the non-overriding function also specifying a
default argument that is a constant expression with the same value.
Rationale
Default arguments are determined by the static type of the object. If a default argument is different for a parameter in an overriding function,
the value used in the call will be different when calls are made via the base or derived object, which may be contrary to developer expectations.
Requiring that multiple default arguments for the same parameter be constant expressions allows compliance checks for this rule to be
decidable.
Example
int32_t x();
class Base
{
public:
virtual void good1( int32_t a = 0 );
virtual void good2( int32_t a = x() );
virtual void bad1 ( int32_t a = 0 );
virtual void bad2 ( int32_t a );
virtual void bad3 ( int32_t a = x() );
};
class Derived : public Base
{
public:
void good1( int32_t a = 0 ) override; // Compliant - same default used
void good2( int32_t a ) override; // Compliant - no default specified
void bad1 ( int32_t a = 1 ) override; // Non-compliant - different value
void bad2 ( int32_t a = 2 ) override; // Non-compliant - no default in base
void bad3 ( int32_t a = x() ) override; // Non-compliant - not constant
};
void f( Derived & d )
{
Base & b = d;
b.good1(); // Will use default of 0
d.good1(); // Will use default of 0
b.good2(); // Will use default of x( )
d.good2( 0 ); // No default value available to use
b.bad1(); // Will use default of 0
d.bad1(); // Will use default of 1
b.bad2( 0 ); // No default value available to use
d.bad2(); // Will use default of 2
}
Copyright The MISRA Consortium Limited © 2023