C++ Class Constructor Member Initialization

Introduction

A better, more efficient way to initialize an object of a class is to use the constructor's member initializer list in the definition of the constructor:

#include <iostream> 

class MyClass //ww  w.  j a v a2  s .c o m
{ 
public: 
    int x, y; 
    MyClass(int xx, int yy) 
         : x{ xx }, y{ yy } // member initializer list 
    { 

    } 
}; 

int main() 
{ 
    MyClass o{ 1, 2 }; // invoke a user-defined constructor 
    std::cout << o.x << ' ' << o.y; 
} 

A member initializer list starts with a colon, followed by member names and their initializers, where each initialization expression is separated by a comma.

This is the preferred way of initializing class data members.




PreviousNext

Related