I have a vector of Student objects which I want to sort using #include <algorithm> and sort(list.begin(), list.end());
In order to do this, I understand that I need to overload the "<" operator but after trying (and failing) with several methods suggested online, I am running out of ideas.
Here is my latest attempt:
In Student.h...
...
using namespace std;
class Student
{
friend bool operator <(const Student& first, const Student& second);
public:
...
private:
...
};
And in Student.cpp...
...
#include "Student.h"
using namespace std;
...
bool operator <(const Student& first, const Student& second)
{
return first.Name() < second.Name();
}
where "Name()" is a constant function which returns a string.
The program compiles and runs, but my operator function is never called during the sort and when I tried comparing two Student objects like s1 < s2 I got an "error: overloaded operator not found"
How can I correctly overload this operator so that my sort will work as I intend?
You didn't say which compiler you were using, but I suspect you're using a fairly recent one that implements the "friend is not a declaration" rule. The friend statement inside the class doesn't serve as a function declaration; other modules that include Student.h don't see any declaration of the function. It's visible only inside the Student.cpp file. (Older compilers don't have this rule, and treat a friend declaration as a function declaration.)
The function doesn't need to be a friend, since it doesn't use any private members of the Student class (I'm assuming Name() is public). Move the function declaration outside the class, and replace "friend" with "extern", and it should work.
It is possible to make the operator a member function, as some posters above suggested, but it isn't necessary. Making comparison operators member functions is generally frowned upon, because it means that the two arguments aren't treated symmetrically (one is the invisible "this" argument, the other is a normal function argument), which can lead to surprising results in some cases (for example, different type conversions may be applied to the arguments).
I wouldn't use a friend here, and I'm not sure it works at all. What I would use is...
class Student
{
public:
bool operator< (const Student& second) const;
};
bool Student::operator< (const Student& second) const
{
return (Name() < second.Name());
}
Note the trailing const, indicating that within operator<, *this is constant.
EDIT I cannot delete this answer because it was accepted, but I would if I could. I also can't replace it with a correct one. See Drew Dormanns comment below, and Ross Smiths answer.
By the way, with a function this simple I would personally just do this, unless the style guide bans the definition of functions inside class definitions:
class Student
{
friend bool operator <(const Student& first, const Student& second)
{
return first.Name() < second.Name();
}
...
};
This form of the "friend" declaration lets you define a non-member operator< inside the body of the class. It's still a friend, so Name() can be private if desired.
Well, you could do it as an internal operator:
class Student
{
public:
bool operator <(const Student& second) const;
...
private:
...
};
With an implementation comparing 'this' to second. The question in my mind is: Does the 'Name' method come in a const flavor? Because if it doesn't, then you can't write a const method that uses it.
Related
I have a class that represents a special number.
class SecretInteger
{
private:
unsigned int *data;
size_t length;
public:
SecretInteger operator+(const SecretInteger other) const;
}
I can't allow any other part of my code have access to the data variable. However, my operator+ function MUST be able to see it. Usually in this case I know that using the friend keyword is the only way to do it. However when I write:
friend SecretInteger operator+(const SecretInteger other);
It claims that the operator+ cannot be declared as friend, even though I've previously wrote friend std::ostream& operator<<(std::ostream& stream, const SecretInteger val); and it works fine.
What options do I have available to me? If I have a public method like
const *unsigned int getData() const; I think even then it doesn't actually make the variable returned const right? I'd really prefer not to have a getData() method and instead just declare the functions that have access as friend.
You don't declare a member function as a friend, friend is to give non-member functions access to internals, and a one operand overload of operator+ is a member function.
In any event, if you implement the binary operators properly, you shouldn't need to give out friendship at all. Implement += as a member function (no need for friend, a class is always "friends" with itself), then implement a non-member + operator in terms of +=, which uses +='s access to the internals to avoid the whole issue of friendship.
The basic rules for overloading can be found here and should help a lot.
I've got these instructions for an assignment that have put me through a loop here. I need to overload the insertion operator to print out an objects datamembers. However, it states that the overloader has to be a non-friend helper operator.
If that's the case, how can it ever access the private datamembers if its not a 'friend'? And if this is possible, why should I avoid using 'friend'?
Here is what it says word for word:
a helper non-friend operator that inserts the stored string into the left ostream operand.
This operator prefaces the string with the number of the insertion and increment that number
I'm somewhat new to C++ so I really appreciate the help.
If it's not a friend, it needs to use the object's public interface (ergo, you need to write the object's public interface to include the access required by the insertion operator).
For example, you might do something like this:
class thing {
std::string name;
public:
std::string get_name() const { return name; }
// ...
};
std::ostream &operator<<(std::ostream &os, thing const &t) {
return os << t.get_name();
}
Note that I'm definitely not recommending this as good practice--rather the contrary, I think it's often a better idea for the insertion operator to be a friend. But if you're in a class and you're prohibited from doing things the right way, you do what you have to...
Following is the abstraction of string class.
class string {
public:
string(int n = 0) : buf(new char[n + 1]) { buf[0] = '\0'; }
string(const char *);
string(const string &);
~string() { delete [] buf; }
char *getBuf() const;
void setBuf(const char *);
string & operator=(const string &);
string operator+(const string &);
string operator+(const char *);
private:
char *buf;
};
string operator+(const char *, const string &);
std::ostream& operator<<(std::ostream&, const string&);
I want to know why these two operator overloaded functions
string operator+(const char *, const string &);
std::ostream& operator<<(std::ostream&, const string&);
are not class member function or friend functions? I know the two parameter operator overloaded functions are generally friend functions (I am not sure, I would appreciate if you could enlighten on this too) however my prof did not declare them as friend too. Following are the definitions of these function.
string operator+(const char* s, const string& rhs) {
string temp(s);
temp = temp + rhs;
return temp;
}
std::ostream& operator<<(std::ostream& out, const string& s) {
return out << s.getBuf();
}
Could anyone explain this with a small example, or direct me to similar question. Thanks in Advance.
Regards
The friend keyword grants access to the protected and private members of a class. It is not used in your example because those functions don't need to use the internals of string; the public interface is sufficient.
friend functions are never members of a class, even when defined inside class {} scope. This is a rather confusing. Sometimes friend is used as a trick to define a non-member function inside the class {} braces. But in your example, there is nothing special going on, just two functions. And the functions happen to be operator overloads.
It is poor style to define some operator+ overloads as members, and one as a non-member. The interface would be improved by making all of them non-members. Different type conversion rules are applied to a left-hand-side argument that becomes this inside the overload function, which can cause confusing bugs. So commutative operators usually should be non-members (friend or not).
Let's talk about operator +. Having it as a non member allows code such as the following
string s1 = "Hi";
string s2 = "There";
string s3;
s3 = s1 + s2;
s3 = s1 + "Hi";
s3 = "Hi" + s1;
The last assignment statement is not possible if operator+ is a member rather than a namespace scope function. But if it is a namespace scope function, the string literal "Hi" is converted into a temporary string object using the converting constructor "string(const char *);" and passed to operator+.
In your case, it was possible to manage without making this function a friend as you have accessors for the private member 'buf'. But usually, if such accessors are not provided for whatever reason, these namespace scope functions need to be declared as friends.
Let's now talk about operator <<.
This is the insertion operator defined for ostream objects. If they have to print objects of a user defined type, then the ostream class definition needs to be modified, which is not recommended.
Therefore, the operator is overloaded in the namespace scope.
In both the cases, there is a well known principle of Argument Dependent Lookup that is the core reason behind the lookup of these namespace scope functions, also called Koenig Lookup.
Another interesting read is the Namespace Interface Principle
Operators can be overloaded by member functions and by standalone (ordinary) functions. Whether the standalone overloading function is a friend or not is completely irrelevant. Friendship property has absolutely no relation to operator overloading.
When you use a standalone function, you might need direct access to "hidden" (private or protected) innards of the class, which is when you declare the function as friend. If you don't need this kind of privileged access (i.e. you can implement the required functionality in terms of public interface of the class), there's no need to declare the function as friend.
That's all there is to it.
Declaring a standalone overloading function as friend became so popular that people often call it "overloading by a friend function". This is really a misleading misnomer, since, as I said above, friendship per se has nothing to do with it.
Also, people sometimes declare overloading function as friend even if they don't need privileged access to the class. They do it because a friend function declaration can incorporate immediate inline definition of the function right inside the class definition. Without friend one'd be forced to do a separate declaration and a separate definition. A compact inline definition might just look "cleaner" in some cases.
I'm a bit rusty with C++ overloads but I would complete the above answers by this simple memo :
If the type of the left-hand operand is a user-defined type (a class, for instance), you should (but you don't have to) implement the operator overloading as a member function. And keep in mind that if these overloads -- which will most likely be like +, +=, ++... -- modify the left-hand operand, they return a reference on the calling type (actually on the modified object). That is why, e.g. in Coplien's canonical form, the operator= overloading is a member function and returns a "UserClassType &" (because actually the function returns *this).
If the type of the left-hand operand is a system type (int, ostream, etc...), you should implement the operator overloading as a standalone function.
By the way, I've always been told that friend keyword is bad, ugly and eats children. I guess it's mainly a matter of coding style, but I would therefore advice you to be careful when you use it, and avoid it when you can.
(I've never been faced to a situation where its use was mandatory yet, so I can't really tell ! )
(And sorry for my bad English I'm a bit rusty with it too)
Scy
I'm wondering why the () operator override can't be "friend" (and so it needs a "this" additional parameter) while the + operator needs to be friend like in the following example:
class fnobj
{
int operator()(int i);
friend int operator+(fnobj& e);
};
int fnobj::operator()(int i)
{
}
int operator+(fnobj& e)
{
}
I understood that the + operator needs to be friend to avoid the "additional" extra this parameter, but why is that the operator() doesn't need it?
You have overloaded the unary plus operator. And you probably didn't want to do that. It does not add two objects, it describes how to interpret a single object when a + appears before it, the same as int x = +10 would be interpreted. (It's interpreted the same as int x = 10)
For the addition operator, it is not correct that "the + operator needs to be friend".
Here are two ways to add two fnobj objects:
int operator+(fnobj& e);
friend int operator+(fnobj& left, fnobj& right);
In the first form, this is presumed to be the object to the left of the +. So both forms effectively take two parameters.
So to answer your question, instead of thinking that "operator() doesn't need friend", consider it as "operator() requires this" Or better still, "Treating an object as a function requires an object".
You didn't understand this correctly (and aren't using it correctly as well).
There are two ways in C++ to define a binary operator for a class, either as a member function
class A
{
public:
int operator+ (A const& other);
};
or as a free function
class A {};
int operator+ (A const& lhs, A const& rhs);
What you are currently mixing up is that you can declare and define this free function in the class scope as friend, which will allow the function to use private members of the class (which is not allowed in general for free functions).
I feel I have a bit of a hole in my understanding of the friend keyword.
I have a class, presentation. I use it in my code for two variables, present1 and present2, which I compare with ==:
if(present1==present2)
Here's how I defined the operator == (in class presentation):
bool operator==(const presentation& p) const;
However, I was told that using friend and defining it outside of the class is better:
friend bool operator==(presentation&, presentation&);
Why? What's the difference between the two?
Your solution works, but it's less powerful than the friend approach.
When a class declares a function or another class as friend it means that friend function or class have access to the declaring class' privates and protected members. It's as if the declared entity was a member of the declaring class.
If you define operator==() as a member function then just like with the friend case the member function has full access to the class' members. But because it is a member function it specifies a single parameter, as the first parameter is implied to be this: an object of type presentation (or a descendent thereof). If, however, you define the function as a non-member then you can specify both parameters, and this will give you the flexibility of comparing any two types that can cast into a presentation using that same function.
For example:
class presentation {
friend bool operator==(const presentation&, const presentation&);
// ...
};
class Foo : public presentation { /* ... */ };
class Bar : public presentation { /* ... */ };
bool operator==(const presentation& p1, const presentation& p2)
{
// ...
}
bool func(const Foo& f, const Bar& b, const presentation& p)
{
return f == b || f == p );
}
Lastly, this raises the question "why the friend declaration?". If the operator==() function does not need access to private members of presentation then indeed the best solution is to make it a non-member, non-friend function. In other words, don't give a function access privileges which is doesn't need.
In the first case, your function operator== is a nonstatic class member. It has therefore access to private and protected member variables.
In the second case, the operator is externally declared, therefore it should be defined as a friend of the class to access those member variables.
An operator implemented as a method, can only be called, if the left hand side expression is a variable (or a reference to the object) of the class, the operator is defined for.
In case of an operator== usually you are interested in comparing two objects of the same class. Implementation, as a method solves your problem here.
Imagine however, that you write a string class and you want an operator, to work in this scenario:
const char *s1 = ...
MyString s2 = ...
if(s1 == s2){...
To make the expression s1 == s2 legal, you have to define an opetator== as a function external to MyString class.
bool operator==(const char *, const MyString&);
If the operator needs an access to the private members if your class, it has to be a friend of your class.
In case of operators << and >>, that work on streams, you define an operator, whose left operand is a stream instance and the right one is your class, so they can't be methods of your class. Like in the example above, they have to be functions external to your class and friends, if the access to private members is required.
I like Benoit's answer (but I can't vote it up), but I figure an example wouldn't hurt to clarify it. Here's some Money code I have (assume everything else is placed right):
// header file
friend bool operator ==(const Money, const Money); // are the two equal?
// source file
bool operator ==(const Money a1, const Money a2)
{
return a1.all_cents == a2.all_cents;
}
Hope that helps.
Take a look at this sorta duplicate here: should-operator-be-implemented-as-a-friend-or-as-a-member-function
What is important to point out, this linked question is about << and >> which should be implemented as friends since the two operand are different types.
In your case it makes sense to implement it as part of the class. The friend technique is used (and useful) for cases where more than one type is used and often does not apply to == and !=.