java_doctor_101
java_doctor_101

Reputation: 3357

Use of references in c++

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

Answers (2)

Wagner Patriota
Wagner Patriota

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:

  • if you use void push(const int &x); --- you can use const OR non-const values!
  • if you use void push(int &x); --- you can use ONLY non-const values!

The basic rule is:

  • My function doesn't need to change the value of parameters: use void push(const int &x);
  • My function needs to change the value of parameters: use 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

Igor Popov
Igor Popov

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

Related Questions