0

I am going through some code and I am having dificulty in comprehending the syntax:

  struct Foo {

  int val_;

  Foo(int v) : val_(v) {}  //--->THIS LINE

  };

The colon : seems like a member access operator.

Can I get a clear explanation the above line?

Michael Myers
  • 184,092
  • 45
  • 284
  • 291
munish
  • 4,173
  • 13
  • 51
  • 77

2 Answers2

3

Its initializing val_ to v.

See: Constructor Initialization Lists

Daniel A. White
  • 181,601
  • 45
  • 354
  • 430
  • Foo(**int v**) or foo() does it makes any differnce.Is parameter **int v** required for this initialization.if not why is that parameter there – munish May 02 '11 at 18:40
  • @munish Whatever you are passing into the constructor as the parameter v is the value to which `val_` is initialized, so yes, you do need the parameter for the constructor. – jonsca May 02 '11 at 18:46
  • 1
    Though you can use initializer lists with no constructor parameters. For example, `Foo() : val_(5) {}` would cause every default-constructed `Foo` to have 5 as the initial value of member `val_`. – aschepler May 03 '11 at 18:26
1

Structures in C++ can have constructors just like classes do. This is initializing the public variable val_ to v just as if you had val_ = v; in the constructor body. See this thread for their benefits in terms of efficiency.

Community
  • 1
  • 1
jonsca
  • 9,627
  • 26
  • 54
  • 61