0

please take your time viewing the code below and answer my queries regarding it

class Vector
{
public:
    int x, y;
    /* Constructor / destructor / Other methods */
    Vector operator + (Vector & OtherVector);
    Vector & operator += (Vector & OtherVector);
};

Vector Vector::operator + (Vector & OtherVector)  // LINE 6
{
    Vector TempVector;
    TempVector.x = x + OtherVector.x;
    TempVector.y = y + OtherVector.y;
    return TempVector;
}

Vector & Vector::operator += (Vector & OtherVector)
{
    x += OtherVector.x;
    y += OtherVector.y;
    return * this;
}

Vector VectorOne;
Vector VectorTwo;
Vector VectorThree;

/* Do something with vectors */
VectorOne = VectorTwo + VectorThree;
VectorThree += VectorOne;

This code was taken off from a book but its not explained very well in there. Specifically I am not able to understand the program from line 6. Neither the constructor nor the operator overloading. Please explain how are operator overloading and the copy constructors working in this program.

Edit: Why are we using the reference operator?

Aditya
  • 91
  • 1
  • 9
  • I just want to point out that `operator+` is typically implemented in terms of `operator+=`. – chris Jul 12 '12 at 16:33
  • 2
    Do you have a *specific* question about the constructor or operator overloading? What, *precisely* do you not understand? – Robᵩ Jul 12 '12 at 16:35
  • I cannot understand how is it working, even the syntax. Or if my question is too vague can someone post some link where operator overloading and copy constructors are explained in depth. – Aditya Jul 12 '12 at 16:40
  • @Aditya, The former has a great reference [here](http://stackoverflow.com/questions/4421706/operator-overloading). – chris Jul 12 '12 at 16:41
  • You want us to explain some of the fundamental aspects of C++? Would a book not be a better option? – Dennis Jul 12 '12 at 16:42
  • 1
    @Dennis, The ironic part is that this question arose from a book. There's a list of [good books](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), too, if you're interested, OP. – chris Jul 12 '12 at 16:43
  • @Dennis It wasn't explained well in the book which I am currently reading thats why I had to turn to this. – Aditya Jul 12 '12 at 16:44
  • @chris - I think Alanis missed this one. – Dennis Jul 12 '12 at 16:46
  • @Aditya - yes, sorry I should have read more carefully. – Dennis Jul 12 '12 at 16:47

5 Answers5

1
6:   Vector operator + (Vector & OtherVector);
7:   Vector & operator += (Vector & OtherVector);

Those declare operator overloading. They are necessary to indicate that you indeed want to overload operators. More on the return values below:

10: Vector Vector::operator + (Vector & OtherVector)
11: {
12:  Vector TempVector;
13:  TempVector.x = x + OtherVector.x;
14:  TempVector.y = y + OtherVector.y;
15:  return TempVector;
16: }

Returns a copy of TempVector which adds the x and y components of the vector. This allows for the following usage (provided that the assignment operator has been defined as well:

24: Vector VectorOne;
25: Vector VectorTwo;
26: Vector VectorThree;
27: /* Do something with vectors */
28: VectorOne = VectorTwo + VectorThree;

17: Vector & Vector::operator += (Vector & OtherVector)
18: {
19:  x += OtherVector.x;
20:  y += OtherVector.y;
21:  return * this;
22: }

This one is the same as above with the slight difference that we are adding to the calling instance instead of to a temporary variable. This results in returning *this. this is a pointer to the current instance of the class so in order to get its value you need to use the star dereferencing operator (correct me if I'm wrong on the name of the operator).

ApplePie
  • 8,814
  • 5
  • 39
  • 60
1

The operator+ is creating a new instance of the Vector class, putting the sums of the x and y elements of the two inputs into that new instance, then returning the new instance. At least IMO (and I can't imagine many disagreeing) it would be better written something like:

Vector Vector::operator+(Vector const &otherVector) const {
    // ...
}

...qualifying both the function itself and its right input as const, since it's not intended to modify either one. The qualification on the function basically refers to the left operand, so this is basically saying that when we do something like a = b + c;, neither b nor c will be modified (i.e., exactly what you'd normally expect). This allows (among other things) a temporary object of type Vector to be used as an operand, as well as assuring that you don't unintentionally modify an input.

operator+= modifies its left operand, so it just adds the x and y elements from the other vector to itself. Then it returns a reference to the (modified version of) the operand that was supplied as the left operand. This allows operator chaining, such as:

Vector a, b, c;

// code to initialize a, b and c here

a += (b += c);

Again, it would benefit from taking the input by reference to const though:

Vector &Vector::operator+=(Vector const &other) {
    // ...
}

In this case we cannot (and don't want to) const qualify the function itself, because it does modify its left operand (again, exactly what you'd expect: in a += b, we expect a to change and b to remain unchanged).

At least as you've shown it, the class definition doesn't contain an explicit copy constructor, which means if you copy an object of this class, the compiler will synthesize a copy constructor for you. Under the circumstances that should be fine -- the only data in the class is two ints, which will normally be fine with a member-wise copy (which is what the compiler will generate). The most common reason for an explicit copy constructor is a class that contains one or more pointers to objects it owns (in which case you also want to see the rule of the three/five).

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
1

Line 6 overloads the '+' operator while line 14 overloads the '+=' operator. For example:

Vector v1,v2,v3;

v1 += v2; // Line 14 takes care of this one

v3 = v1 + v2; // Line 6 takes care of this one

The big difference here is that the '+=' overload modifies the values inside the instance the operator is being called on (v1 in the example above), while the '+' operator takes the two instances and generates a third with the modified values. Hope this is clear.

ryanbwork
  • 2,123
  • 12
  • 12
1

This code doesn't include a copy constructor, However copy constructor is used in scenarios where you dyamically allocate members of a class, so that the program should not crash once an instance or object goes out of scope because the destructor will deallocate the dynamically allocated memory if you have included delete or free for new or malloc respectively.

Now coming to operator overloading at line 6: When you add to objects like

VectorOne = VectorTwo + VectorThree;

line 6 function is called, it creats temporary object to do addition on members of VectorTwo and VectorThree and then returns the temperory object to VectorOne and hence VectorOne recieves bitwise copy of TempVector. . Keep in mind that VectorTwo is implicitly passed to this function because it is at the left of the overloaded operator When you add objects likeVectorThree += VectorOne; , function operator+=() is called and VectorThree is implicitly passed to the function and then the function returns the bitwise copy of the object which is implicitly passed to the function. Keyword this points to the object which has called the function in this case VectorThree. And then the return copy is save in VectorThree again.

Umer Farooq
  • 7,356
  • 7
  • 42
  • 67
  • Thanks alot, specially for pointing the mistakes and explaining it. – Aditya Jul 12 '12 at 18:01
  • @UmerFarooq: He left a "thank you" comment for *every* reply he got. That's not to say he shouldn't accept one or that yours is a poor choice, only that the comment doesn't seem to indicate that he found your answer a lot better than any of the others. – Jerry Coffin Jul 13 '12 at 03:43
  • I am not insisting him Sir. I said If he finds it Satisfying then he should accept it. – Umer Farooq Jul 13 '12 at 05:42
0

Lines 6 and 7 are prototypes for overloaded operators.

Vector & operator += (Vector & OtherVector);

The return type is a Vector reference and the Argument is a vector reference. The operator is the += operator. That function will be called on the following line:

VectorThree += VectorOne;

The definition is on line 17. You can see that they act the same as typical member functions (they have a this constant, which is implicitly used to locate x and y). As is typical of the += operator, the function works such that the contents of the argument VectorOne are unchanged, and the contents of VectorThree are set to their original value plus VectorOne, and the new value of VectorThree is returned. You can verify for yourself that the += operator for integral types works in the same way with the following snippet:

int a = 1, b = 2, c;
c = (a += b);
cout << "a: " << a << " b: " << b << " c: " << c << endl;

It's important to note that the implementation of operators for classes can follow any model they want. For instance, the += operator for strings is the in-place append operator. It is generally true that if a class defines a + operator and a += operator, the + operator will take 2 arguments, perform some operation, and return a third value, and the += operator will take 2 arguments, perform some operation, modify one of its arguments, and return that value.

It's also important to note that since the value of the arguments for both operators is not changed, you can make them const, like such:

Vector operator + (const Vector & OtherVector);
Vector & operator += (const Vector & OtherVector);

The reason for this is if you wanted to pass a const variable to an operator that didn't declare its arguments const, you would not be able to, even if it didn't change them. The following is illegal if const is not specified for the argument of += and legal if it is:

Vector value1;
const Vector value2;

value1 += value2;
Wug
  • 12,956
  • 4
  • 34
  • 54