Reputation: 149
I am newbie to c++, I have not yet seen this kind of constructor, what does it do?
class A {
int x;
public:
A(int xx):x(xx) {}
};
int main() {
A a(10);
A b(5);
return 0;
}
Is the code above valid?
What does this constructor do? A(int xx):x(xx) means what? A cast?
Upvotes: 1
Views: 117
Reputation: 18974
The string :x(xx)
is called an initializer. As you can see it's valid on only a constructor. The effect is to initialize x with the value xx. So your code makes two A objects - one has an x of 10 and the other of 5.
This is more efficient than letting it be initialized and then changing its value in the body of the constructor by writing x=xx;
Upvotes: 1
Reputation: 5949
The code is valid: The member variable "x
" is being set a value in the "base/member initializer list".
This type of initialization is required when you are initializing a value for a reference member, constant member, or to forward arguments to the base constructor.
It is optional in other cases, like this one, where the value could have been explicitly set in the constructor body (but this is arguably faster, since it is initialized as memory is allocated).
Upvotes: 0
Reputation: 6424
A(int xx) : x(xx)
initializes the data member x
with the value of xx
.
Upvotes: 0
Reputation: 49261
That's a constructor with an initializer.
The x(xx)
initializes x with the value of xx
Upvotes: 0
Reputation: 272687
The stuff after the :
and before the body (the empty braces) is an initializer list. It initializes the member variable x
with xx
.
See this section from the C++ FAQ: http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6.
Upvotes: 2
Reputation: 3835
That is called an initialization list. The private variable x will be initialized with xx when the constructor is called.
Upvotes: 0
Reputation: 34625
is the code above valid?
Yes.
what does this constructor do? A(int xx):x(xx) means what?
It is called initializer list which copies xx
to the class member x
.
Upvotes: 4