Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ beginner: what is the point of using a variable by reference if using "const"?

I was wondering about the logic in this function declaration:

CMyException (const std::string & Libelle = std::string(),...

What is the point of using a variable by reference? Usually you pass a variable by reference whenever it may be modified inside... so if you use the keyword const this means it'll never be modified.

This is contradictory.

May someone explain this to me?

like image 220
Olivier Pons Avatar asked Dec 28 '22 06:12

Olivier Pons


2 Answers

Actually reference is used to avoid unnecessary copy of the object.

Now, to understand why const is used, try this:

std::string & x= std::string(); //error

It will give compilation error. It is because the expression std::string() creates a temporary object which cannot be bound to non-const reference. However, a temporary can be bound to const reference, that is why const is needed:

const std::string & x = std::string(); //ok

Now coming back to the constructor in your code:

CMyException (const std::string & Libelle = std::string());

It sets a default value for the parameter. The default value is created out of a temporary object. Hence you need const (if you use reference).

There is also an advantage in using const reference : if you've such a constructor, then you can raise exception like this:

throw CMyException("error"); 

It creates a temporary object of type std::string out of the string literal "error", and that temporary is bound to the const reference.

like image 200
Nawaz Avatar answered Dec 29 '22 18:12

Nawaz


Some arguments might use quite some memory. If you pass an argument as value it will be copied and the copy will be passed to the method.

Passing them as reference will only pass the pointer to the method which is faster and saves the memory for the copy.

like image 22
juergen d Avatar answered Dec 29 '22 19:12

juergen d