Search code examples
c++initializationctor-initializer

Only static and const variables can be assign to a class?


I am learning C++. Just curious, can only static and constant varibles be assigned a value from within the class declaration? Is this mainly why when you assign values to normal members, they have a special way doing it

void myClass::Init() : member1(0), member2(1)
{
}

Solution

  • This looks like it is supposed to be a constructor; if it is, it should have no return type, and it needs to have the same name as the class, e.g.,

    myClass::myClass()
        : member1(0), member2(1)
    {
    
    }
    

    Only a constructor can have an initializer list; you can't delegate that type of initialization to an Init function.

    Any nonstatic members can be initialized in the constructor initializer list. All const and reference members must be initialized in the constructor initializer list.

    All things being equal, you should generally prefer to initialize all members in the constructor initializer list, rather than in the body of the constructor (sometimes it isn't possible or it's clumsy to use the initializer list, in which case, you shouldn't use it, obviously).