0

I saw the following code in a book and am wondering what is going on:

class shiftedList{

      int* array;
      int offset, size;

public:       

         shiftedList(int sz) : offset(0), size(sz){
               array = new int[size];
        }        

}

what is going on with offset(0) and size(sz) in the constructor of the class?

Thanks for the help.

Stefano Sanfilippo
  • 32,265
  • 7
  • 79
  • 80
Pujun
  • 1
  • 7
    Look up `initializer lists`. – Jashaszun Jul 25 '14 at 21:25
  • The fields after the colon will be initialized with those values, in this case offset will be 0 and size will be initialized to sz. See [link](http://stackoverflow.com/questions/926752/why-should-i-prefer-to-use-member-initialization-list) – tehwallz Jul 25 '14 at 21:25

1 Answers1

1

They are just initializers as part of the constructor.

So in this specific case it is equivalent to

shiftedList(int sz) {
   offset = 0;
   size = sz;
   array = new int[size];
}   

Except that the compiler can do better optimization, and the initialization may not actually result in any code.

There are case where initializer list has to be used, specifically those where a reference variable is being initialized.

Soren
  • 14,402
  • 4
  • 41
  • 67