could u pls help mi,i realli need your help.i am trying to do a simple addition of using class vector.i hope u could guide mi.i'm nt sure whether i'm doing it right anot.i will be so appericated for all the help frm u.

example:A vector can be represented in Cartesian coordinates (a, b, c).
Suppose vector X is (a1, b1, c1) and Y is (a2, b2, c2).
Addition:X + Y = (a1+a2, b1+b2, c1+c2).

example result:
Outputs A + B (8,14,9)

class myVector
  int x,y,z;
      myVector operator+(const myVector &mv)const;

myVector myVector::operator +(const myVector &mv)const  //Addition
  myVector mv;
  mv.x = x + mv.x;
  mv.y = y + mv.y;
  mv.z = z + mv.z;
  return mv;

//main program to test the class
int main()

  myVector A,B,C;
  cout << "Enter first vector, format (a,b,c): ";
  cin >> A;
  cout << "Enter second vector, format (a,b,c): ";
  cin >> B;
  C = A + B;
  cout<<"Addition A+B = "<< C << endl;

return 0;

Hello lisa, thank you for the question.

You're actually very close. You want to modify the class on the left side of the operator though. Try this:

void myVector::operator +(const myVector &mv)
this->x += mv.x;
this->y += mv.y;
this->z += mv.z;

If you want to be able to print the myVector class, you also need to overload the << operator:

ostream& myVector::operator << (const ostream &o) const;
o << this->x << endl;
o << this->y << endl;
o << this->z << endl;
return o;

That should have you fixed up and ready to go. Let me know if it doesn't work. I haven't overloaded a << operator on a class in a while.

I hope this information was helpful.

- Eddie


All Answers

Answers by Expert:

Ask Experts




I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by ExpertRating.com. I also know a good deal about graphics via OpenGL, and GUIs.


I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2017 About.com. All rights reserved.