Question

Today I discovered that it is possible to declare a function in a header with one signature, and implement it in the source file with different (similar) signature. For example, like this :

// THE HEADER  example.hpp

#ifndef EXAMPLE_HPP
#define EXAMPLE_HPP

int foo( const int v );

#endif

// THE SOURCE FILE example.cpp

#include "example.hpp"

int foo( int v )   // missing const
{
  return ++v;
}

Is this allowed? Or is this the compiler's extension (I am using g++ 4.3.0) ?

EDIT I am compiling with pedantic and maximum possible warning level, and I am still not getting a warning or an error.

Was it helpful?

Solution

For the purposes of determining a function signature, any top level const qualifier is ignored. This is because it does not affect function callers. Function parameters are passed by value in any case so the function cannot affect the arguments passed in.

The top level const does affect the body of the function. It determines whether or not the parameter can be changed in the body of the function. It is the same function as the declaration though.

So yes, it is legal and the declaration and definition refer to the same function and not an overload.

Standard reference: 8.3.5 [dcl.fct] / 3: "[...] The type of a function is determined using the following rules. [...] Any cv-qualifier modifying a parameter type is deleted. [...] Such cv-qualifiers affect only the definition of the parameter within the body of the function; they do not affect the function type. [...]"

OTHER TIPS

Since int is a basic value type, the const modifier does not have any effect here. No matter what you do to your int in the function, this will never be seen by the caller.

You can't do this with int&. In that case, the presence or absence of const is really relevant for the caller, since the int referred to could be modified.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top