0

I am new to c++ programing.This is an example in Bjarne Stroustrup's c++ book. Can any one explain to me what this line does

X(int i =0) :m{i} { } //a constructor ( initialize the data member m )

Can anyone tell me what does this ':' symbol does.I am new to c++ programs.

class X { 
 private: //the representation (implementation) is private
 int m;
 public: //the user interface is public
 X(int i =0) :m{i} { } //a constructor ( initialize the data memberm )
 int mf(int i) //a member function
 {
   int old = m;
   m = i; // set new value

   return old; // return the old value
 }
};

X var {7}; // a variable of type X initialized to 7

int user(X var, X∗ ptr) {
  int x = var.mf(7); //    access using . (dot)
  int y = ptr−>mf(9); //   access using -> (arrow)
  int z = var.m; //error : cannot access private member
}
Azad
  • 5,144
  • 4
  • 28
  • 56
gokul
  • 109
  • 10
  • 2
    I would only point you in the right direction - look for `initializer list`. By the way, the comment says it anyway – skratchi.at Nov 05 '19 at 06:14
  • As above commented you need to know about initializer list. Check this link and learn https://en.cppreference.com/w/cpp/utility/initializer_list – Nikhil Badyal Nov 05 '19 at 06:45

1 Answers1

2

Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. 

#include<iostream> 

using namespace std; 

class Point { 
    int x; 
    int y; 

public: 
    Point(int i = 0, int j = 0) : x(i), y(j) {}  

    /*  The above use of Initializer list is optional as the  
        constructor can also be written as: 

        Point(int i = 0, int j = 0) { 
            x = i; 
            y = j; 
        } 
    */    

    int getX() const {return x;} 
    int getY() const {return y;} 
}; 

int main() { 
  Point t1(10, 15); 

  cout << "x = " << t1.getX() << ", "; 
  cout << "y = " << t1.getY(); 

  return 0; 
} 

/* OUTPUT: 
   x = 10, y = 15 
*/

The above code is just an example for syntax of the Initializer list. In the above code, x and y can also be easily initialed inside the constructor. But there are situations where initialization of data members inside constructor doesn’t work and Initializer List must be used. Following are such cases:

1) For initialization of non-static const data members: const data members must be initialized using Initializer List. In the following example, “t” is a const data member of Test class and is initialized using Initializer List. Reason for initializing the const data member in initializer list is because no memory is allocated separately for const data member, it is folded in the symbol table due to which we need to initialize it in the initializer list. Also, it is a copy constructor and we don’t need to call the assignment operator which means we are avoiding one extra operation.

Serhiy
  • 1,332
  • 1
  • 16
  • 24