Explain this please

Explain line 5 of the code please!

1
2
3
4
5
6
7
  struct studentRecord
{
int score; 
string* name; 
int operator != (studentRecord x) const
{ return (score!= x.score);}
};
Reading and understanding the code becomes much easier if the code is formatted in a more readable way.

1
2
3
4
5
6
7
8
9
struct studentRecord
{
	int score; 
	string* name; 
	int operator != (studentRecord x) const
	{
		return (score!= x.score);
	}
};


It defines a != (not-equal-to) operator that you can use to compare two studentRecord objects.

1
2
3
4
5
6
7
8
9
10
studentRecord a{5, nullptr};
studentRecord b{9, nullptr};
if (a != b)
{
	std::cout << "The score is not the same" << std::endl;
}
else
{
	std::cout << "The scores are the same" << std::endl;
}
1. Why is const put "there" in line 5?I mean what does it mean when it's written after, say, (studentRecord x)?

2.From line 5-8; are we defining a function? If yes what is its return type..int or int operator?

3.Thanks for the answer! (:
1. Read here - http://stackoverflow.com/questions/3141087/what-is-meant-with-const-at-end-of-function-declaration

2. Yes a function is defined, you're returning an integer. This is called operator overloading. You can read more about it here - https://www.google.se/#q=operator+overloading+c%2B%2B

Or watch a bunch of videos of people explaining it - https://www.youtube.com/results?search_query=operator+overloading+c%2B%2B
Last edited on
Why int? The relational and comparison operators should return bool.
See http://www.cplusplus.com/doc/tutorial/operators/

Furthermore, one does usually implement only operators < and ==, because the standard library has templates for the other operators that work if these two are defined.
Yes a function is returned, you're returning an integer
errm, o you mean "defined" not "returned"? :-)

In brief:

1. The const in that position is a promise that the function, will not modify any members of the object for which it is called. The compiler will make sure this promise is kept.

2. Yes we're defining a function that returns an int. This scenario is called operator overloading, and lets you use the special word "operator" to define a function in such a way, that when the operator is used the function is called instead of the built in operator.
In Peter87's example, a!=b is equivalent to a.operator!=(b) but you can't call it directly like that, just imagine that "operator!=" is a function name.

3. Read the links suggested above.

Topic archived. No new replies allowed.