gotchacppCritical
What is this weird colon-member (" : ") syntax in the constructor?
Viewed 0 times
weirdconstructorcolonsyntaxmemberthethiswhat
Problem
Recently I've seen an example like the following:
What does this strange
Are there any other esoteric language features like this, you'll never find in an ordinary C++ book?
#include
class Foo {
public:
int bar;
Foo(int num): bar(num) {};
};
int main(void) {
std::cout << Foo(42).bar << std::endl;
return 0;
}What does this strange
: bar(num) mean? It somehow seems to initialize the data member, but I've never seen this syntax before. It looks like a function/constructor call but for an int. This makes no sense to me.Are there any other esoteric language features like this, you'll never find in an ordinary C++ book?
Solution
It's a member initialization list. You should find information about it in any good C++ book.
You should, in most cases, initialize all member objects in the member initialization list (however, do note the exceptions listed at the end of the FAQ entry).
The takeaway point from the FAQ entry is that,
All other things being equal, your code will run faster if you use initialization lists rather than assignment.
You should, in most cases, initialize all member objects in the member initialization list (however, do note the exceptions listed at the end of the FAQ entry).
The takeaway point from the FAQ entry is that,
All other things being equal, your code will run faster if you use initialization lists rather than assignment.
Context
Stack Overflow Q#1711990, score: 250
Revisions (0)
No revisions yet.