Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behavior of function overloading with const

I'm working on g++ and here I have tried to overload a function by just adding const to parameter. It works fine and when it runs, it calls the function without const

  1. Is this behavior specified in the C++ standard?
  2. What the reason it calls the function without const

    void print(const std::string& str){std::cout << "const" << str << std::endl;}
    
    void print(std::string& str){std::cout << str << std::endl;}
    
    int main()
    {
       std::string temp = "hello";
       print(temp);
       return 0;
    }
    
like image 571
Nayana Adassuriya Avatar asked Mar 17 '26 11:03

Nayana Adassuriya


2 Answers

Reference bindings are an identity category §13.3.3.1.4) but since the latter is more cv-qualified, for §13.3.3.2, the non-const is preferred (sample code from the standard):

int f(const int &);
int f(int &);

int i;
int j = f(i); // calls f(int &)
like image 51
Marco A. Avatar answered Mar 18 '26 23:03

Marco A.


That is standard behavior. Any other behavior would lead to crazy behavior. In particular, the non-const function would not be callable at all.

like image 27
Ben Avatar answered Mar 18 '26 23:03

Ben



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!