Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a function with different signature

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.

like image 784
BЈовић Avatar asked Nov 18 '10 08:11

BЈовић


People also ask

Can a function with same name have different signatures?

you can define more than one method with same name but there signature must be different.

Can two functions have the same signature?

A function's signature includes the function's name and the number, order and type of its formal parameters. Two overloaded functions must not have the same signature.

What is the type signature of a function?

A function signature (or type signature, or method signature) defines input and output of functions or methods. A signature can include: parameters and their types. a return value and type. exceptions that might be thrown or passed back.

What is the signature of a function in C++?

C++ Reference. Programming Terms. Function Signatures. A function signature consists of the function prototype. What it tells you is the general information about a function, its name, parameters, what scope it is in, and other miscellaneous information.


1 Answers

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. [...]"

like image 125
CB Bailey Avatar answered Oct 16 '22 07:10

CB Bailey