Main Content

MISRA C++:2008 Rule 8-3-1

Parameters in an overriding virtual function shall either use the same default arguments as the function they override, or else shall not specify any default arguments

Description

Rule Definition

Parameters in an overriding virtual function shall either use the same default arguments as the function they override, or else shall not specify any default arguments.

Rationale

If the default parameter of a virtual function is different in an overriding function, then the function call uses different values when invoked using different classes of a hierarchy. Such behavior is unexpected for a class hierarchy. Consider this class hierarchy:

class Base{
public:
virtual foo(int x = 0);
//...
};

class Derived: public Base{
public:
virtual foo(int x = 1) override; //Noncompliant

};
The virtual function foo() has different default parameters depending on whether base::foo() or Derived::foo() is invoked. This behavior is unexpected and can result in unexpected results.

Polyspace Implementation

Polyspace® reports violations of this rule if an overriding virtual function has a different default parameter compared to the virtual function it overrides. Specifying no default parameter is compliant with this rule and Polyspace does not report violations when overriding virtual functions specify no default parameters.

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

In this example, the virtual function myDerivedClass<T>::function() overrides myClass<T>::function() but has a different default parameter. Polyspace reports a violation of this rule.

template  <class T>
class myClass{
public:
virtual myClass<T> function(int val = 0);

};

template<class T>
class myDerivedClass: public myClass<T>{
	public:
	virtual myClass<T> function(int val = 10) override; //Noncompliant
	
};

void func(){
	myClass<int> a;
	myDerivedClass<float> b;
}

Check Information

Group: Declarators
Category: Required

Version History

Introduced in R2013b

expand all