One of the most common tasks a constructor carries out is initializing data members. In the Counter class the constructor must initialize the count member to 0. You might think that this would be done in the constructor’s function body, like this:
count()
{ count = 0; }
However, this is not the preferred approach (although it does work). Here’s how you should initialize a data member:
count() : count(0)
{ }
The initialization takes place following the member function declarator but before the function body. It’s preceded by a colon. The value is placed in parentheses following the member data.
If multiple members must be initialized, they’re separated by commas. The result is the initializer list (sometimes called by other names, such as the member–initialization list).
Thursday, October 30, 2008
Initializer List
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment