Use of references in c++ -


i trying wrap head around use of references. have understood references need constant , alias variable. while writing code stack, when passed value reference push function. had include "const" keyword. need know why necessary.

in short why works

class stack { public:     void push(const int &x); };  void stack::push(const int &x) {     // code push }   int main()  {     stack y;     y.push(12);     return 0;  } 

but not?

class stack { public:     void push(int &x); };   void stack::push(int &x)  {      // code push  }  int main() {     stack y;     y.push(12);     return 0; } 

if use

int main() {     stack y;     int x = 12;     y.push(x);     return 0; } 

you see works if remove "const". it's because 12 constant, x not constant!

in other words:

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

the basic rule is:

  • my function doesn't need change value of parameters: use void push(const int &x);
  • my function needs change value of parameters: use void push(int &x); [notice here if planning change value of parameter, of course can't constant 12, variable value 12, that's difference!]

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -