Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct Constructor Syntax [duplicate]

Tags:

c++

struct

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)
    {
    }
};
like image 209
Cemre Mengü Avatar asked Feb 05 '12 00:02

Cemre Mengü


1 Answers

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) { }
};
like image 139
dee-see Avatar answered Sep 21 '22 17:09

dee-see