Main Content

MISRA C++:2008 Rule 14-6-2

The function chosen by overload resolution shall resolve to a function declared previously in the translation unit

Description

Rule Definition

The function chosen by overload resolution shall resolve to a function declared previously in the translation unit.

Rationale

In general, you cannot call a function before it is declared, so you expect a function call to resolve to a previously declared function. However, in case of overload resolution of a function call inside a template, this expectation might not be satisfied. The resolution of this overload occurs at the point of template instantiation, not at the point of template definition. So, the call might resolve to a function that is declared after the template definition and lead to unexpected results. See examples below.

To satisfy the expectation that a function call always resolves to a previously declared function, declare the overloads of a function prior to calling it. Alternatively, use the scope resolution operator :: or parenthesis to explicitly call a specific previously declared function and bypass the overload resolution mechanism.

Polyspace Implementation

The checker flags a call to a function or operator in a function template definition if the function or operator is declared after the template definition.

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

void show (int);

namespace helpers {
	struct params {
		operator int () const;
	};
}

template <typename T> void displayParams(T const & arg) {
	show(arg);    //Non-compliant
	::show(arg);  //Compliant 
	(show)(arg);  //Compliant
}

namespace helpers {
	void show (params const &);
}

void main() {
	helpers::params aParam;
	displayParams(aParam);
}

In this example, the call show(arg) in the template displayParams resolves to helpers::show(), but a developer or code reviewer might not expect this call resolution, since helpers::show() is declared later. Polyspace flags this call.

The calls ::show(arg) and (show)(arg) explicitly indicate the previously declared function show() declared in the global namespace. Polyspace does not flag these calls.

Check Information

Group: Templates
Category: Required

Version History

Introduced in R2013b