C & C++

C & C++

By DeepSource

Found const data members CXX-W2010

Anti-pattern

Const data members are only allowed to be initialized by the constructor of the class, and never after. And unlike in other languages, they are still instance dependent types. Having such members is rarely useful, and makes the class only copy-constructible but not copy-assignable.

If it was intended to be a constant value attached to the class or struct type itself consider using a static const member.

Bad practice

class Foo {
private:
    const int bar;
public:
    Foo(): bar(10) {}
}

Recommended

class Foo {
private:
    static const int bar = 10;
public:
    Foo() {}
}