Search code examples
c++constantsdatamemberdata-members

Is it appropriate to declare a non-static constant data member inside a class while coding?


data member inside a class can be const but only if its static. otherwise we need to have a constructor to initialize a constant inside a class.

can we declare a const data member inside a class? //this was an interview question

It seems to me that we can, but is it appropriate for a programmer to declare a constant inside a class.

please give some explanation/reasons, why we can or cannot do?


Solution

  • Off course you can :

    struct A
    {
        A() : a(5)
        {
        }
        const int a;
    };
    
    int main()
    {
       A a;
    }
    

    This means that the data member a, inside struct A is not going to change.