Can we define two functions with same name but different parameters?

Viewed 16259

I am confused when we need to define another function we can give it a different name. But on LeetCode discussion, I found a popular post in which there are two functions with same name, but having different parameters.

int longestPalindromeSubseq(string s) {
    return longestPalindromeSubseq(0,s.size()-1,s); 
}
int longestPalindromeSubseq(int l, int r, string &s) {
    if(l==r) return 1;
    if(l>r) return 0;  //happens after "aa" 
    return s[l]==s[r] ? 2 + longestPalindromeSubseq(l+1,r-1, s) : 
        max(longestPalindromeSubseq(l+1,r, s),longestPalindromeSubseq(l,r-1, s)); 
}
3 Answers

I am confused when we need to define another function we can give it a different name.

The is the one of the most basic feature of C++: function overloading. In C you can't have two functions with the same name, at all. In C++, it's entirely possible as long as the function function signature is different, ie two functions having the same name but different set of parameters.

https://en.wikipedia.org/wiki/Function_overloading

What you are looking at is called "Function overloading" in C++. The c++ compiler creates signatures based on the declaration of the function. You can have entirely different signatures of a function with the same name.

In the example posted by you, the signature changes because of the difference in the parameters passed.

here is what Signature stands for : the information about a function that participates in overload resolution (13.3): its parameter-type-list (8.3.5) and, if the function is a class member, the cv-qualifiers (if any) on the function itself and the class in which the member function is declared.

In a strongly typed language, the parser can (in principle) make the difference between functions with the same name but a different argument list (number and type of the arguments), at function-declaration time as well as function-call time. This is called function overloading and also applies to class methods.

C++ supplies this feature.


In some cases, there are ambiguities and the compiler will tell you. In C++ you cannot declare functions that only differ by their return type.

Related