After creating objects and calling an overloaded operator, what will be printed in the console?

#include <iostream>
using namespace std;

class Base
{
    int* data;
public:
    Base(int size, int value=0)
    {
        data = new int(value);
    }

    ~Base() { delete data; }

    Base &operator+=(Base src)
    {
        *data += *src.data;
        return *this;
    }

    operator int() { return *data; }
};

int main()
{
    Base a(2);
    Base b(2, 10);
    a += b;
    cout << b << endl;
    return 0;
}
Explanation
Since the object is passed to the += operator by value, therefore in the line a += b temporary copy of the object b will be created. Since the copy constructor is not overloaded, pointers to data, the object b, and its temporary copy will point to the same memory area. On exit from the body of the += operator, the destructor for the temporary copy of the object b will be called , which will clean the memory.

Слідкуй за CodeGalaxy

Мобільний додаток Beta

Get it on Google Play
Зворотній Зв’язок
Cosmo
Зареєструйся Зараз
або Підпишись на майбутні тести