user1219733
user1219733

Reputation: 23

Need help in understanding a small part of a basic class in c++?

Can somebody explain me what is being done in the CVector CVector::operator+ (CVector param). How does the dot operator work with temp. I understand when you do object.function() but how does it make sense to do object.object does this just set them both equal to each other? Confused!!

#include <iostream>
using namespace std;

class CVector {
  public:
int x,y;
CVector () {};
CVector (int,int);
CVector operator + (CVector);
};

CVector::CVector (int a, int b) {
  x = a;
  y = b;
}

CVector CVector::operator+ (CVector param) {
   CVector temp;
   temp.x = x + param.x;
   temp.y = y + param.y;
   return (temp);
 }

 int main () {
   CVector a (3,1);
   CVector b (1,2);
   CVector c;
   c = a + b;
   cout << c.x << "," << c.y;
   return 0;
 }

Upvotes: 2

Views: 58

Answers (2)

nvuono
nvuono

Reputation: 3363

I think you're asking about the following:

temp.x = x + param.x;
temp.y = y + param.y;    

In this case the . operator just accesses the members of the temp CVector object.

You'll see in your class CVector that you have public instance members x and y. Each instance of a CVector object then has its own x and y int variables.

class CVector { 
  public: 
     int x,y; 
     ...
}

So temp.x is accessing the value for reading or assignment the same way you'd access any other local variable in a code block:

void SomeCalc(CVector temp){
   int sum;
   int z = 1;
   temp.x = 2;
   sum = z + temp.x; // sum now equals 3
}

Upvotes: 0

David Robinson
David Robinson

Reputation: 78600

This is called operator overloading. What it is doing in this case is allowing you to add two of CVector objects together, as shown in the main function.

When a + b occurs in the main function, the operator+ method of the a object is called, with b as the param. It thus constructs a temp object that combines the coordinates of the two, and returns it.

ETA: Rereading your question, I think you might also be asking what the line

temp.x = x + param.x;

means. Note that C++ objects don't just have functions they can call (like object.function()), they have members, which are themselves variables that can be accessed and changed. In this case, x and y are ints that belong to the CVector class. Read this tutorial closely.

Upvotes: 3

Related Questions