Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ overloading with one parameter const

Tags:

c++

Why is following not allowed in C++

#include <iostream>

class Sample {
public:
  void Method(char x);
  void Method(char const x);
};

void Sample::Method(char x) {
  char y = x;
}

void Sample::Method(char const x) {
  char y = x;
}

int main() {
  Sample s;
  return 0;
}
like image 843
Avinash Avatar asked May 14 '12 11:05

Avinash


People also ask

Can const function be overloaded?

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

Why we use const in operator overloading in C++?

The const qualifier ensures that the parameter (param) is not altered inside the operator=() method. The above method alters the right hand side operand 'param' after assigning the value to the left hand side operand.

What is const parameter?

A constant parameter, declared by the keyword const , is a read-only parameter. This means that we can not modify the value of the constant parameter in the function body. Using the const keyword tells the compiler that the value of that parameter will not be changed inside the function.

How is it possible to have both const and non-const version of a function?

There are legitimate uses of having two member functions with the same name with one const and the other not, such as the begin and end iterator functions, which return non-const iterators on non-const objects, and const iterators on const objects, but if it's casting from const to do something, it smells like fish.


1 Answers

Why is following not allowed in C++?
The reason is the very same that the compiler gives you as an compilation error:
Because they are ambiguous!

Why are these methods ambiguous?
Short answer: Because the C++ Standard says so.

What is the rationale behind these overloaded methods being ambiguous?
The compiler does not know whether the caller wants to treat the value of the passed argument as an const or not, there is no way for the compiler to determine that with the information at hand.

Note the emphasis on pass by value here, the argument is being passed by value, and hence the ambiguity. If the argument was passed by reference then the compiler knows for sure how the caller wants to treat the argument because then the actual object itself is being passed, and hence compiler can make a selection of the proper overload.

The following example gives a clearer idea to the explanation above.

Online Sample:

class Sample 
{
    public:
        void Method(char &x){}
        void Method(char const x){}
        void Method(char const &x){}
};


int main() 
{
     Sample s;
     return 0;
}
like image 144
Alok Save Avatar answered Nov 07 '22 12:11

Alok Save