Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function overloading with const parameters

Function overloading can happen between two member functions which have the same number of parameters, if one of them is declared as const.

But what if one function has a const argument, another has non-const argument of same type? Will it work for references and pointers? If C++ provides it, why does it provide? Please share the reason with me if you know.

Below is the example that helps you in understanding the above scenario.

void fun(const int i)
{
    cout << "fun(const int) called ";
}
void fun(int i)
{
    cout << "fun(int ) called " ;
}
int main()
{
    const int i = 10;
    fun(i);
    return 0;
}

Output: Compiler Error: redefinition of 'void fun(int)'

void fun(char *a)
{
  cout<<"non-const fun() called";
}

void fun(const char *a)
{
  cout<<"const fun() called";
}

int main()
{
  const char *ptr = "GeeksforGeeks";
  fun(ptr);
  return 0;
}

Output: const fun() called

Why is the second one allowed in C++?

like image 429
ranganath111 Avatar asked Oct 02 '12 18:10

ranganath111


People also ask

What is the use of const overloading in C++?

Overloading on the basis of const type can be useful when a function return reference or pointer. We can make one function const, that returns a const reference or const pointer, other non-const function, that returns non-const reference or pointer.

What happens if you overload a method with multiple parameters?

If two overloaded method contains parameters, and one parameter is normal, another is constant, then this will generate error. But if the arguments are reference or pointer type, then it will not generate error.

How to overload member methods in C++?

C++ allows member methods to be overloaded on the basis of const type. Overloading on the basis of const type can be useful when a function return reference or pointer.

What is function overloading in programming?

Function overloading is a feature of object oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading.


1 Answers

The first one's parameters are top-level const. This means that the function can't change the parameter's value, however, the caller doesn't care: The callee gets a copy of the argument, so if a parameter has top-level const, it's an implementation detail. Note that the following works:

void f(int); // forward declare

void g(){ f(42); }

void f(int const i){ /*...*/ } // define above declared function

For the second set of overloads, the const isn't top-level anymore. It describes whether or not the callee can change what the pointer points at. As a caller, you do care about that. It's not just an implementation detail anymore.

like image 83
Xeo Avatar answered Sep 30 '22 11:09

Xeo