0

Possible Duplicate:
C++ initialization lists

class Base
{
public:
int m_nValue;

Base(int nValue=0)
    : m_nValue(nValue)
{
}
};

In this code, is the constructor initializing m_nvalue member variable? I am not sure of this syntax:

Base(int nValue=0) : m_nValue(nValue) {}

We normally write it as:

Base(int nValue) { m_nValue = nValue;}

Can some one explain the above syntax of C++?

Community
  • 1
  • 1
Anup Buchke
  • 5,210
  • 5
  • 22
  • 38
  • 1
    http://stackoverflow.com/a/4589256/735756 – tmaric Jan 19 '13 at 01:08
  • 1
    Whoever the "we" is who normally writes it the second way is wrong. For primitive types, they're equivalent, but for class types, the second way first default-initializes the variables, then copies new values into them, which (a) adds an otherwise-unnecessary requirement that the types be default-initializable, (b) is slower, and (c) makes exception guarantees harder to write. – abarnert Jan 19 '13 at 01:13
  • `We normally write it as` No we don't – Lightness Races in Orbit Jan 19 '13 at 02:47

3 Answers3

3

This syntax:

Base(int nValue=0)
: m_nValue(nValue)

is called the member initializer. It will initialize m_nValue with given nValue. This syntax is usually preferred in C++ since it is executed before the body of the constructor.

taocp
  • 23,276
  • 10
  • 49
  • 62
1

It's called member initializer list.

The member initializer list consists of a comma-separated list of initializers preceded by a colon. It’s placed after the closing parenthesis of the argument list and before the opening bracket of the function body

Conceptually, these initializations take place when the object is created and before any code within the brackets is executed.

Note: You can’t use the member initializer list syntax with class methods other than constructors.

billz
  • 44,644
  • 9
  • 83
  • 100
0

The way of initializing a variable in your code is called as member initializer list. Generally we use such list to initialize const member variable (normal - non const also) we because at the time of construction we can give some value to const variable.

Second type of Initialization is basically a normal Parametrised constructor. That is used when you are having a object and at the time of creation of object you want to initialize the member variable.

Astro - Amit
  • 767
  • 3
  • 15
  • 36