2

Possible Duplicate:
Initializing in constructors, best practice?

I'm new to C++.

Suppose we have this class definition:

Class MyClass {
  int a;
  int b;

  //....
}

I would like to know which is the difference between the two class contructors:

public: 
    MyClass(int a, int b) : a(a), b(b) {}

and (i would say Java-style):

MyClass(int a, int b) {

this->a = a;
this->b = b;
}

I suppose the first is better in C++; right? why?

Community
  • 1
  • 1
Aslan986
  • 9,984
  • 11
  • 44
  • 75

1 Answers1

8

The first one (using initializer list) initializes the data members to the given values. The second one initializes them first, then assigns them the values. That is the reason the first is prefered. There is no unnecessary assignment operation there.

This is particularly important when your data members are expensive to construct and/or assign to. Also bear in mind that some types are not default constructable, making it mandatory to use the initializer list.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480