DEV Community

Discussion on: When to use const in C++? Part II: member variables

Collapse
 
pgradot profile image
Pierre Gradot

In my opinion, when you create a class Foo, there is a broader question than "should member bar be const or more?".

This broader question = "is Foo a value object or not?"

If Foo is in fact 3DCoordinate, then Foo should be copyable and its members data x, `y and z should not be const.

If Foo is BankAccount, then it should be impossible to copy an object and its members data number and owner should be const.

For me, the question "const or not?' has to be answered based on semantic first, not on "technical details" :)

Collapse
 
sandordargo profile image
Sandor Dargo

Semantics are definitely important, but it's also good if technically your code follows your intentions. I definitely used const members in a way where they were semantically correct, but I didn't consider the technical implications.