0

I have a structure defined in the following way:

struct struct_name
{
    int x;
    region y;

    bool operator == (const struct_name& other) const;
};

I do not understand the last line in the body of the structure. What does it do?

Roman
  • 124,451
  • 167
  • 349
  • 456

2 Answers2

6

Declares operator== for this struct. This operator will allow you to compare struct objects in an intuitive way:

struct_name a;
struct_name b;
if( a == b )
// ...

bool operator == (const struct_name& other) const;
^^^^              ^^^^^............^        ^^^^^-- the method is `const` 1
^^^^              ^^^^^............^
^^^^              ^^^^^............^--- the `other` is passed as const reference
^^^^
^^^^-- normally, return true, if `*this` is the same as `other`

1 - this means, that the method does not change any members


EDIT: Note, that in C++, the only difference between class and struct is the default access and default type of inheritance (noted by @AlokSave) - public for struct and private for class.

Kiril Kirov
  • 37,467
  • 22
  • 115
  • 187
  • note that it only defines that such an operator is exists (the linker will search for it). There is no implementation for this function defined in this piece of code (it is probably defined somewhere else). – Philipp Aumayr Apr 30 '13 at 14:31
  • @PhilippAumayr - that's why I wrote `declares`, not `defines`. – Kiril Kirov Apr 30 '13 at 14:32
  • +1: nitpick: *"the only difference between class and struct....."* and that inheritance by default is `private` for class while `public` for structure. – Alok Save Apr 30 '13 at 14:41
3

It declares a function. The function's name is operator==. It returns bool and takes a single argument of type const struct_name&. It final const in the line says that it is a const member function, which means that it doesn't modify the state of the struct_name object it is called on.

This is known as operator overloading.

Community
  • 1
  • 1
Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324