c++pass-by-reference-value

Difference between const reference and reference


void setage(const int&a);
void setage(int&a);

What is the difference between this two functions? When this function is called?


Solution

  • Given the overload set:

    void setage(int&a) { std::cout << "&"; }
    void setage(const int&a) { std::cout << "&c"; }
    

    the first function is called only with variables that are non-const:

    int a = 42;
    setage(a);  // prints &
    

    The second function is called if you pass it a variable that is const, or if you pass it a literal value:

    int const b = 42;
    setage(b);  // prints c&
    setage(42);  // prints c&
    

    Note that if this overload set is written within a class, the same rules apply, and which function is called still depends on whether the passed in argument is a literal, non-const variable, or const variable.