Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others


0 votes
in Technique[技术] by (71.8m points)

c++ - What is this weird colon-member (" : ") syntax in the constructor?

Recently I've seen an example like the following:

#include <iostream>

class Foo {
  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 member variable but I've never seen this syntax before. It looks like a function/constructor call but for an int? Makes no sense for me. Perhaps someone could enlighten me. And, by the way, are there any other esoteric language features like this, you'll never find in an ordinary C++ book?

Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers


47.2k users