0

Does constructor parameter initialization list works different from using assignment operator inside the constructor?

I have the following code:

class Person1
{

public:

    int age;
    string name;
    double weight;
    double height;
    Person1();
    Person1(int age, string name, double weight, double height);
};

Person1::Person1()
{
    
}

Person1::Person1(int age, string name, double weight, double height)

//: m_age{age}, m_name{name}, m_weight{weight}, m_height{height}

{

//    this->age = age;

//    this->name = name;

//    this->height = height;

//    this->weight = weight;
    
    age = age;
    name = name;
    height = height;
    weight = weight;
}

void ModifyPerson1(Person1 person1)

{

    person1.name = "Jerry";
    cout << person1.age << " " << person1.name  << " " << person1.weight << " " << person1.height << endl;
}

int main()
{

    Person1 person1(15,"Tom",140,5);
    cout << person1.age << " " << person1.name  << " " << person1.weight << " " << person1.height << endl;
    ModifyPerson1(person1);
    cout << "Name after modification : " << person1.name << endl;
    return 0;

}

The OP for the above code is :

-272632464 6.95313e-310 2.12202e-314

-272632464 Jerry 6.95313e-310 2.12202e-314

Name after modification :

Program ended with exit code: 0

If I use the either the initialization list or this-> operator for the constructor, the output is as expected:

15 Tom 140 5

15 Jerry 140 5

Name after modification : Tom

Program ended with exit code: 0

I am seriously not able to understand why the behavior differs.

Community
  • 1
  • 1
rn4
  • 21
  • 1
  • 3
    Because `age = age;` assigns the local variable `age` to itself. – tkausl May 08 '18 at 05:08
  • morale: read warnings – Swift - Friday Pie May 08 '18 at 05:57
  • Yes, initialiser lists apply special context rules, such that the thing being initialised must be a (non-static) member of the class, ignoring the usual rule that context vars (in this case arguments) win. You can get the behaviour explicitly in your function using this-> – Gem Taylor May 08 '18 at 10:52

0 Answers0