14

Possible Duplicate:
What does a colon following a C++ constructor name do?

I found the example below online however the syntax for the constructor confuses me a little bit especially the : symbol. Could anyone please give me a brief explanation ? Thanks.

struct TestStruct {
    int id;
    TestStruct() : id(42)
    {
    }
};
Alexey
  • 1,198
  • 1
  • 15
  • 35
Cemre Mengü
  • 18,062
  • 27
  • 111
  • 169
  • possible duplicate of [What does a colon following a C++ constructor name do?](http://stackoverflow.com/questions/1272680/what-does-a-colon-following-a-c-constructor-name-do). See also list of duplicates [here](http://stackoverflow.com/questions/3504215/what-does-the-colon-mean-in-a-constructor) – CB Bailey Feb 05 '12 at 00:18

2 Answers2

31

The constructor initializes id to 42 when it's called. It's called an initliazation list.

In your example, it is equivalent to

struct TestStruct {
    int id;
    TestStruct()
    {
        id = 42;
    }
};

You can do it with several members as well

struct TestStruct {
    int id;
    double number; 
    TestStruct() : id(42), number(4.1)
    {
    }
};

It's useful when your constructor's only purpose is initializing member variables

struct TestStruct {
    int id;
    double number; 
    TestStruct(int anInt, double aDouble) : id(anInt), number(aDouble) { }
};
dee-see
  • 23,668
  • 5
  • 58
  • 91
  • 1
    "Same thing" is a bit cavalier, and probably fairly misleading. – Kerrek SB Feb 05 '12 at 00:20
  • 5
    Cool, thanks, but it's not only "useful", but it is an utter necessity for variables that must be initialized non-trivially, such as base subobjects, constants or references. – Kerrek SB Feb 05 '12 at 00:25
  • Certainly, but I figured that this level of answer would suit the question and that OP would seek further reading on the subject once he gets there. But you are right, it's more than just a useful feature. – dee-see Feb 05 '12 at 00:27
1

It's a constructor initialization list. You can learn more about it here:

http://www.learncpp.com/cpp-tutorial/101-constructor-initialization-lists/

SGosal
  • 11
  • 1