0

Possible Duplicate:
Class construction with initial values

While I was looking at c++ example in http://en.wikipedia.org/wiki/Delegation_pattern I noticed something I haven't seen before:

C() : i(new A()) { }

My question is: How is this line of code any different from:

C() {
    i = new A();
}

What does : after constructor do? What does the brackets around new A() do?

Community
  • 1
  • 1
karthaxx
  • 11
  • 1
  • possible duplicate of [Class construction with initial values](http://stackoverflow.com/questions/7207884/class-construction-with-initial-values) and also: http://stackoverflow.com/questions/4589237/c-initialization-lists – Brian Roach Mar 30 '12 at 18:11
  • I didn't know what it's called so I didn't know what to search for, sorry for duplicate, I'll read topics you linked. Thanks. – karthaxx Mar 30 '12 at 18:13

1 Answers1

4

Its called initialization list. It is used to initialize the data members of a class.

C() {
    i = new A(); // i is not initialized here, here assignment is taking place.
}
Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
  • There is also a multitude of reasons to do those in the same order as their declarations. – Ed Heal Mar 30 '12 at 18:12
  • 1
    Also, before C++11, const members could only be initialized with member initializer syntax. – chris Mar 30 '12 at 18:13
  • @EdHeal Because the sequence of initialization of class variables are just the sequence of declaring them. – xis Mar 30 '12 at 18:16
  • @xis - Say, for example, one is an array and the other is the size of the array. Things get undefined. – Ed Heal Mar 30 '12 at 18:32