1

I have this following class, I overload the + operator on my class vector. I have defined my own copy constructor as well. This is the code ::

class vector {

public:
    int size;

    vector() {
        cout << "In empty constructor\n";
        this->size = 5;
        cout << "size = " << size << endl;
    }

    vector(int size) {
        cout << "In size constructor\n";
        this->size = size;
        cout << "size = " << size << endl;
    }

    vector(const vector &v) {
        cout << "inside copy constructor\n";
        this->size = v.size;
        cout << "size = " << this->size << endl;
    }

    vector operator ++() {
        vector v = *this;
        (this->size)++;
        return v;
    }

    vector operator ++(int a) {
        cout << "a = " << a << endl;
        vector v = *this;
        (this->size)++;
        return v;
    }

    vector operator+(vector &a) {
        vector  v;
        v.size = this->size + a.size;
        return v;
    }

    vector& operator=(vector &a) {
        cout << "Inside = assignment operator\n";
        this->size = a.size;
        return *this;
    }

    ~vector() {
        cout << "In destructor for vector of size = " << this->size << endl;
    }

};

And this is main ::

int main(int argc, char** argv) {
    vector v;
    vector v2(27);
    vector v3 = v + v2;
    return 0;
}

I inserted cout statements in my constructors to see which constructor is called when. According to what I understand, in my line vector v3 = v + v2 the copy constructor shall be called, since we are initializing the object during its call, so after the computation v + v2 copy constructor shall be called. But it doesn't. I also tried to overload the = operator to check if it is assigning values, but that is not happening either.

The output of the about program is this ::

In empty constructor
size = 5
In size constructor
size = 27
In empty constructor
size = 5
In destructor for vector of size = 32
In destructor for vector of size = 27
In destructor for vector of size = 5

In my overloaded function of +, i return the resultant vector by value, so it should be copied I believed.

Why doesn't the copy constructor get called??

Thanks for any help in advance.

Ideone link (if that helps) :: http://ideone.com/S9EtjR

user007
  • 2,156
  • 2
  • 20
  • 35

0 Answers0