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?
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?
A single colon in this context is used to signal that you are using an initializer list. An initializer list is used to:
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:
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()
.
It is used to initialize references. In c++ you cannot assign or modify references, so in class they can only be "assigned" with semicolon syntax.
The single colon specifies an initialization list, as the other couple of responses have already stated.
There are a number of gotchas about these lists and constructors in general. C++ does a reasonable job of generating default constructors and copy constructors but if you write your own, it leaves it up to you to handle everything: