Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importance of a singlecolon ":" in C++ [duplicate]

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

Rarely in the regular codes I encounter the a single colon in classes for e.g.:

A::member():b(),c()
{
}

What is the importance of the single colon over here? Why is it used here? Is it mandatory sometimes? If so in which cases?

like image 733
Vijay Avatar asked Nov 27 '22 15:11

Vijay


1 Answers

A single colon in this context is used to signal that you are using an initializer list. An initializer list is used to:

  • Invoke base class constructors from a derived class
  • Initialize member variables of the class

As noted by others, an initializer list can only be used on a class constructor.

While it's also possible to initialize member variables in the body of the constructor, there are several reasons for doing so via the initializer list:

  • Constant pointers or references cannot be initialized from the body of the constructor
  • It is usually more efficient to use the initializer list as it will (from memory) only invoke the constructor for the member, rather than the constructor and assignment operator which can be costly for non-POD types.

Having said all of this, the formatting of your code is a bit odd. In the code that I usually work with, use of an initializer list would be indented like this:

A::A()
    :b(),
     c()
{
}

This makes it more clear to me that the : has no relation to the :: used to define class membership in A::A().

like image 149
LeopardSkinPillBoxHat Avatar answered Dec 11 '22 03:12

LeopardSkinPillBoxHat