Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using class member name in a constructor

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?

like image 506
Dani Avatar asked Jun 12 '26 05:06

Dani


1 Answers

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:

  1. First is the one that constructor receives as an argument &
  2. Second is the member of the class 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);
  1. this is class A pointer.
  2. B() is constructor of type B.
  3. B inside the parenthesis is an instance of type B.
like image 54
Alok Save Avatar answered Jun 13 '26 19:06

Alok Save



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!