Reputation: 3357
I am trying to wrap my head around the use of references. By now I have understood that references need to be constant and they are like alias to a variable. However while writing a code for the stack, when I passed value by reference to the push function. I had to include "const" keyword. I need to know why is that necessary.
In short why does THIS works
class stack
{
public:
void push(const int &x);
};
void stack::push(const int &x)
{
// some code for push
}
int main()
{
stack y;
y.push(12);
return 0;
}
But THIS does not?
class stack
{
public:
void push(int &x);
};
void stack::push(int &x)
{
// some code for push
}
int main()
{
stack y;
y.push(12);
return 0;
}
Upvotes: 1
Views: 115
Reputation: 5674
If you use
int main()
{
stack y;
int X = 12;
y.push(X);
return 0;
}
you will see it works EVEN IF YOU REMOVE THE "const". It's because 12 is constant, but X is not a constant!
In other words:
void push(const int &x);
--- you can use const OR non-const values!void push(int &x);
--- you can use ONLY non-const values!The basic rule is:
void push(const int &x);
void push(int &x);
[notice here that if you are planning to change the value of your parameter, of course it can't be a constant 12, but some variable with value 12, that's the difference!]Upvotes: 2
Reputation: 2620
You call the push method using rvalue (literal 12). In C++ rvalue can be called using only const reference parameters, or in C++11 using the so called rvalue reference (&&).
Upvotes: 0