c++classdestructorcopy-constructorconstruct

Why the result of this program is 3 "born"?And 4 dead


This is main.cpp:

int main() {

    Person arr[2] = {
        Person(18,180),
        Person(20,173)
    };
    arr[0]+arr[1];

    return 0;
}  

This is Person.h:

class Person
{
private:
    int age;
    int height;
public:
    Person(int age=20,int height=180);
    ~Person();
    void operator+(Person);
};

And this is Person.cpp:



Person::Person(int age,int height) {
    (*this).age = age;
    (*this).height = height;
    cout << "I'm born.\n";
}

Person::~Person() {
    cout << "I'm dead.\n";
}

void Person::operator+(Person a) {
    Person result;
    result.age = (*this).age + a.age;
    result.height = (*this).height + a.height;
    cout << result.age << endl;
    cout << result.height << endl;
}

Why the result of this program is 3 "born"?And 4 dead? What are the procedures of initializing the array of objects 'arr'?


Solution

  • The missing born person is a clone! Note operator+ take an argument by value, so the copy constructor is called (the default one in this case). To see this add

    Person::Person(const Person &p) {
        this->age = p.age;
        this->height = p.height;
        cout << "I'm a clone.\n";
    }
    

    to your code - then it is clear why there are 4 people dead in the end. A better idea is you have your odd operator to have this signature to avoid copies and be explicit:

    void Person::operator+(const Person &a) const;
    

    Also, no point in using *this when you have the arrow operator.