Student
Student

Reputation: 452

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.

Upvotes: 0

Views: 2561

Answers (3)

Ayush Mahajan
Ayush Mahajan

Reputation: 649

If you are an Indian and class 12th student this answer is for you...

See code 1 is perfectly fine and will run fine according to all standards of c++. In code 2 you can only initialize static member at the time of declaration if you are using standard older than c++11

Now, what is generally taught in Indian school is standard older than c++11(c++03 I guess). But VS uses latest compiler and compiles code accordingly. Hence, your code runs on VS but is wrong according to book

Upvotes: 0

Peter
Peter

Reputation: 36597

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).

Upvotes: 2

lobo
lobo

Reputation: 164

Prior to c++ 11 you can't initialize a non static variable. You need to use getters and setters.

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

Upvotes: 1

Related Questions