Search code examples
c++classconstructorvisual-studio-2015initializer-list

Cannot initialize a class member?


In my notes that I am going through I came to this page where it shows

class Student{
public:
    Student()
    {
        age = 5; //Initialize age
    };
private:
    int age; // **Cannot initialized a class member**
    string name; // **Cannot initialized a class member**
 };

What does it mean that you can not initialize a class member? This is a topic about constructor initializer list. I have tested in VS using this code and it works fine.

class TestClass
{
    int number = 27; //The member is initialized without a problem.
public:
    TestClass();
    int getNumber(); // Return number
    ~TestClass();
};

I apologize if I am asking a stupid question but I am hoping to learn better by posting this question here.


Solution

  • The second example (initialising non-static class member at point of declaration) is permitted only in C++11 or later.

    The first is valid before C++11, although it is often considered better to implement the constructor using an initialiser list rather than assigning it in the constructor body.

    //  within your definition of class Student
    
    Student() : age(5)
    {
    };
    

    If you intend your code to work with older (pre-C++11) compilers you cannot initialise non-static members at the point of declaration.

    If you intend your code to work only with C++11 (or more recent) compilers then both options are valid, and the choice comes down to coding style (i.e. it is subjective).