// Faan Tone Liu // Demo Program for comp 1672 // Shows how to use the member initializer list in a constructor #include #include using namespace std; // This class has a couple of data members - it's just for example purposes class num_and_name { public: num_and_name(); // default constructor num_and_name(int, string); // constructor void print(); private: int num; string name; }; num_and_name::num_and_name() // the member initializer list comes after : num(0) // a colon after the constructor header. We're // allowed to just initialize some data members. { // The default constructor for our string } // member name is automatically called num_and_name::num_and_name(int n, string s) : num(n), name(s) // the member initialization list is comma { // separated. Here we initialize all data } // members using the member initialize list. void num_and_name::print() { cout << name << ": " << num; } int main() { num_and_name him(25, "Joe"); // On this line, the constructor is called him.print(); // Note that, sure enough, the data members cout << endl; // were properly initialized. }