c++ - Passing const references to functions -


i watching video , saw code:

class dog {     public:         dog() : age(3), name("dummy") {}          void setage(const int &a) { age = a; }      private:         int age;         std::string name; }; 

i curious function signature setage because i've never used const function parameter. i've looked @ several related answers, none seemed answer question.

in such elementary example, it's hard see benefit of passing const reference function.

is there reason why you'd want make reference const? application think of in embedded programming when making copy of variable waste precious space.

are there simple examples, perhaps, impact seen of passing const reference?

thanks, erip

consider following 3 examples:

(i)   void setage(int &a) { age = a; } (ii)  void setage(const int &a) { age = a; }  (iii) void setage(int a) { age = a; }  

further think of class encapsulated object, outside world in general doesn't know what's going on inside.

then, using case (i), caller cannot know a has not been changed afterwards.

int a=3; dog.setage(a);  //case (i): "a" afterwards? 

one not know value a holds after function call -- in fact, function signature tells caller change of a occur.

on other hand, using variant (ii), again pass object via reference, not make copy, tell function memory address can go accss parameter. in contrast case (i), ensure caller "nothing going happen parameter". is, can safely work parameter afterwards , assured has still same value before (--at least in principle, bad things const_cast might happen inside function).

finally, in case (iii), 1 makes copy of int , uses inside function. built-in types int, in fact preferred way pass function parameters. however, might uneffective if object expensive-to-copy.

with regard whole const correctness-topic, see here.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -