Is constructor called in before the data members in C++

618 Views Asked by At

Hello i am new to learning C++. Is constructor created in the order i create it in the class or is it always called first before anything else is created in the class.

#include <iostream>
using namespace std;

class NonStatic 
{
    public:
        int no = 2;

    NonStatic():no(0) {
        
    }
};

int main() {
    NonStatic obj1;
    cout << obj1.no;
    
    return 0;
}

In this class. Will the constructor be created before the data member or after the data member

2

There are 2 best solutions below

0
leslie.yao On BEST ANSWER

For int no = 2;, no is initialized as 2 via default member initializer. For NonStatic():no(0) {}, no is initialized as 0 via member initializer list. Then the default member initializer is ignored, for NonStatic obj1;, obj1.no will be initialized as 0 as the result.

If a member has a default member initializer and also appears in the member initialization list in a constructor, the default member initializer is ignored for that constructor.

About the initialization order, data members are initialized firstly (via default member initializer or member initializer list), then constructor body is executed.

The order of member initializers in the list is irrelevant: the actual order of initialization is as follows:

  1. ...

  2. ...

  3. Then, non-static data member are initialized in order of declaration in the class definition.

  4. Finally, the body of the constructor is executed

0
paxdiablo On

It doesn't really make sense to ask about when the constructor is created, it's code so is created at compile time.

If you're asking which of the default member initialisation int no = 2; or constructor initialisation : no(2) has precedence, it's the latter.

You could assume the class sets it to two then the constructor sets it to zero but that doesn't really make sense. If the constructor is always doing it, the default doesn't matter so will probably do nothing.

Of course, if a different constructor is called that doesn't init no, it will get the default value.