Search code examples
c++constructordatamember

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


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


Solution

  • 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