2

Possible Duplicate:
What is this weird colon-member syntax in the constructor?

Hi,

In Sams Teach Yourself C++ in 21 Days book, Day 12: Implementing inheritance, is this code snippet:

Mammal(): itsAge(2) , itsWeight(5) {}

Is this equivalent to saying?

Mammal() 
{ 
itsAge(2); 
itsWeight(5); 
}

What advantage does the first form have? Especially its usage in the book?

Thanks.

Community
  • 1
  • 1
  • 4
    This is in the FAQ list: [What is this weird colon-member syntax in the constructor?](http://stackoverflow.com/questions/1711990/what-is-this-weird-colon-member-syntax-in-the-constructor) (See especially [Josh's answer](http://stackoverflow.com/questions/1711990/what-is-this-weird-colon-member-syntax-in-the-constructor/1712011#1712011).) Voted to close as a dupe. – sbi Jan 25 '11 at 10:14
  • 2
    These @aali posts are starting to look very much like @SWEngineer posts - in content, frequency and lack of any attempt at self-help. – Paul R Jan 25 '11 at 10:18
  • 1
    @Paul: Interesting observation. Incidentally, aali joined two days ago, which is when SWEngineer was put into suspension for half a year after posting >50 silly questions. I've flagged for the moderators to look at this. – sbi Jan 25 '11 at 10:28
  • @Marc: Wow. Was it obvious that aali was a sockpuppet account? – sbi Jan 25 '11 at 10:59
  • I think "sockpuppet" would be the wrong term; the *same* account, bypassing the suspension. If you see more that are "oddly familiar" we can always break out heavier tools... – Marc Gravell Jan 25 '11 at 11:16
  • @Marc: I meant to ask if there was any other indication that he was the same guy than just the similarity of the questions. But maybe it's better this isn't known too well in the public... Anyway, thanks for taking actions so fast! – sbi Jan 25 '11 at 13:39

2 Answers2

1

The first is initialization list syntax, not function calls like your second snippet. http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
0

Read about Initialization list.

You have to use initialization list to initialize your data members

For example:

class A
{
   int k;
   const int l;
   int & p;

   A(int a, int b, int c) : k(a), l(b), p(c) {} // k,l and p are initialized
};

is correct whereas

class A
{
   int k;
   const int l;
   int & p;

   A(int a, int b, int c){

       k = a ; // assignment
       l = b ; Arghh!!
       p = c ; WTF ??
   }
};

is ill-formed

If your class contains const and reference data members you have to use initialization list.

Community
  • 1
  • 1
Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345