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

#include <iostream>
using namespace std;

class Base
    int* data;
    Base(int size, int value=0)
        data = new int(value);

    ~Base() { delete data; }

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

    operator int() { return *data; }

int main()
    Base a(2);
    Base b(2, 10);
    a += b;
    cout << b << endl;
    return 0;
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.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Sign Up Now
or Subscribe for future quizzes