I am with doubt regarding clean code/coding style, the doubt is, when should I use the keyword const
in C++ constructor parameters. For example, consider the following class:
class A {
public:
B& b;
explicit A (const B& b_): b(b_) {}
};
In this code, I want to initialize the reference b
from the class A
, and at the same time, I want to express that the reference passed as a parameter to the class A
constructor will not be used to change the values of the object b_
. However, the presented code will not compile, and the compiler will present the message:
"error: binding reference of type ‘B&’ to ‘const B’ discards qualifiers"
I know I can use the keyword const
in the b
class attribute, however, it will make the attribute constant, and I do not want to impose this constraint over the attribute. So, I would like to know what should I do in this situation.