When a function takes a parameter as a reference to a const object, I understand that the object passed as argument to it cannot be modified using the reference? So is there any scenarios in C++ where a const object can be modified through a reference to it? If yes, show an example.
When a function takes a parameter as a reference to a const object ,
Share
C++ has a feature called
mutablewhere a data member may be changed even through a const reference:I get the following error:
However, the assignment
g.b = 2;succeeds.This feature is usually used for
privatemember variables only, where the changing of the data member does not affect the outside visible const-ness of the object. For example, it could be used as an optimisation to provide a way to cache previously calculated values.