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)
{
}
};
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) { }
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With