Nagappa
Nagappa

Reputation: 313

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?

Upvotes: 0

Views: 2498

Answers (2)

cigien
cigien

Reputation: 60208

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.

Upvotes: 5

ChrisMM
ChrisMM

Reputation: 10020

The const just means that the function will not change the value. When passing by reference, it's often preferred to pass by constant reference, unless the function is supposed to change the parameter.

As to which function gets called, it would depend on the variable type. See below example.

int a( const int &b ) { return b; }
int a( int &b ) { return ++b; }

int main() {
    int x = 2;
    a( x ); // calls a( int & b )
    a( 5 ); // calls a( const int &b )
    const int y = 7;
    a( y ); // calls a( const int &b )
}

Note that literal values (such as 5 in the above example) can not bind to non-const references.

Upvotes: 1

Related Questions