-2

I actually cannot understand 3rd,4th line in the following code in C++ :

struct POINT {
      int x,y;
      POINT(int x = 0, int y = 0) : x(x), y(y) {}
      bool operator ==(POINT& a) {return a.x==x && a.y==y;}
};

Other examples/explanations are also welcome apart from this code snippet :)

Eric
  • 95,302
  • 53
  • 242
  • 374
Maggi Iggam
  • 682
  • 1
  • 8
  • 20
  • Read a book and/or Google – Levi Jun 03 '15 at 21:27
  • The keywords you're looking for are "operator overloading" – Eric Jun 03 '15 at 21:27
  • @Eric : Thanks :) ! that was helpful but i still can't figure out what the last 2 lines mean ! – Maggi Iggam Jun 03 '15 at 21:31
  • 2nd last line means to initialize x,y to zero for each instance created while last line allows us to compare two structs(points here) directly with '==' . Ex- we have two variables A,B with above point structure. As such we can't compare if (A==B) ... but last line allows us to do so ,hope it makes sense :) – Maggi Iggam Jun 03 '15 at 21:48
  • That solved my problem . Super Thanks :D ! – Maggi Iggam Jun 03 '15 at 21:49

1 Answers1

1

structure is nothing but a class with all its data members and functions defined in public scope. So you can implement any operators which is valid for a class.

If your question is on operator overloading, all overloaded operators can be defined for a class is valid for a structure.

You can refer this Operator overloading question and answer to understand more on operator overloading

POINT(int x = 0, int y = 0) : x(x), y(y) {} //(3rd line)
bool operator ==(POINT& a) {return a.x==x && a.y==y;}//(4th line)

3rd line is a constructor, and 4th line is an operator overloading function for operator ==.

POINT p1(2,3); // 3rd line will get called and update x=2 and y=3

POINT p2; // 3rd line will get called and consider x=0 and y=0 
          //since function definitiion is defaulted with value x=0 and y=0;
if(p2==p1) {....}
  // 4th line will get called and compare P1 and P2
Community
  • 1
  • 1
Steephen
  • 14,645
  • 7
  • 40
  • 47