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?
Actually reference is used to avoid unnecessary copy of the object.
Now, to understand why
constis used, try this: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 toconstreference, that is whyconstis needed:Now coming back to the constructor in your code:
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:
It creates a temporary object of type
std::stringout of the string literal"error", and that temporary is bound to theconstreference.