Reputation: 31559
I know this as this will assign the constructor parameter to the class member:
class A
{
public:
some_type B;
A(some_type B)
{
this->B = B;
}
}
But what will this do:
class A
{
public:
some_type B;
A(some_type B) : B(B)
{
}
}
Will this assign the parameter to itself or the parameter to the class member or do something else?
How are the names in the list after construct thing (I have no idea how its called) resolved?
Upvotes: 2
Views: 190
Reputation: 206508
That Thing is called a Member Initializer List in C++.
There is a difference between Initializing a member using initializer list(2nd Example) and assigning it an value inside the constructor body(1st Example).
When you initialize fields via initializer list the constructors will be called once. The object gets constructed with the passed parameters.
If you use the assignment then the fields will be first initialized with default constructors and then reassigned (via assignment operator) with actual values.
As you see there is an additional overhead of creation & assignment in the latter, which might be considerable for user defined classes.
How are the names in the list after construct thing (I have no idea how its called) resolved?
public:
some_type B;
A(some_type B) : B(B)
{
}
In the above snipet, there are two entities named B
:
A
The variable received as argument in Constructor of A
gets passed as an argument for constructing B
(by calling its constructor) which is member of class A
. There is no ambiguity in names here, the all to constructor is:
this->B(B);
this
is class A
pointer. B()
is constructor of type B
. B
inside the parenthesis is an instance of type B
. Upvotes: 9
Reputation: 9711
In the first situation, your objet will be constructed. In the second, it will be constructed (with default constructor) and assigned.
You might not want assignation (maybe the operator is not defined, or no default constructur or the behaviour is specific, or maybe, in some cases because of performance issues).
Concerning the visibility, in both cases, if you just use B, it's the parameter you're manipulating.
Upvotes: 0
Reputation: 12202
Will this assign the parameter to itself or the parameter to the class member or do something else?
It will assign the parameter to the class member.
How are the names in the list after construct thing (I have no idea how its called) resolved?
This is the initializers list, and though the example can lead to confusion, the id at the left of the parenthesis is a member of the class, while the id (or literal) inside the parenthesis can only be one of the parameters of the constructor: thought that way, there is no ambiguity at all.
The key here is that this list must initialize class members with some value, so if you think of
...: B(B)
as conceptually equivalent to a constructor call:
this->B(B)
... there is no ambiguity.
Upvotes: 2