I wrote an abstraction class for a math object, and defined all of the operators. While using it, I came across:
Fixed f1 = 5.0f - f3;
I have only two subtraction operators defined:
inline const Fixed operator - () const;
inline const Fixed operator - (float f) const;
I get what is wrong here - addition is swappable (1 + 2 == 2 + 1) while subtraction is not (same goes for multiplication and division).
I immediately wrote a function outside my class like this:
static inline const Fixed operator - (float f, const Fixed &fp);
But then I realized this cannot be done, because to do that I would have to touch the class's privates, which results to using the keyword friend which I loath, as well as polluting the namespace with a 'static' unnecessary function.
Moving the function inside the class definition yields this error in gcc-4.3:
error: ‘static const Fixed Fixed::operator-(float, const Fixed&)’ must be either a non-static member function or a non-member function
Doing as GCC suggested, and making it a non-static function results the following error:
error: ‘const Fixed Fixed::operator-(float, const Fixed&)’ must take either zero or one argument
Why can't I define the same operator inside the class definition? if there's no way to do it, is there anyway else not using the friend keyword?
Same question goes for division, as it suffers from the same problem.
If you need reassuring that friend functions can be OK:
http://www.gotw.ca/gotw/084.htm
Which operations need access to
internal data we would otherwise have
to grant via friendship? These should
normally be members. (There are some
rare exceptions such as operations
needing conversions on their left-hand
arguments and some like operator<<()
whose signatures don't allow the *this
reference to be their first
parameters; even these can normally be
nonfriends implemented in terms of
(possibly virtual) members, but
sometimes doing that is merely an
exercise in contortionism and they're
best and naturally expressed as
friends.)
You are in the "operations needing conversions on the left-hand arguments" camp. If you don't want a friend, and assuming you have a non-explicit float constructor for Fixed, you can implement it as:
static inline Fixed operator-(const Fixed &lhs, const Fixed &rhs) {
return lhs.minus(rhs);
}
then implement minus as a public member function, that most users won't bother with because they prefer the operator.
I assume if you have operator-(float) then you have operator+(float), so if you don't have the conversion operator, you could go with:
static inline Fixed operator-(float lhs, const Fixed &rhs) {
return (-rhs) + lhs;
// return (-rhs) -(-lhs); if no operator+...
}
Or just Fixed(lhs) - rhs if you have an explicit float constructor. Those may or may not be as efficient as your friend implementation.
Unfortunately the language is not going to bend over backwards to accommodate those who happen to loathe one of its keywords, so operators can't be static member functions and get the effects of friendship that way ;-p
"That's what friends are for..."
You could add an implicit conversion between float and your type (e.g. with a constructor accepting float)... but I do think using a friend is better.
When you define something like this,
inline const Fixed operator - (float f) const;
you are saying that I want this operator(you are inside the class) to operate on a specific type, float here for example.
Whereas a friend binary operator, means an operation between two types.
class Fixed
{
inline friend const Fixed operator-(const Fixed& first, const float& second);
};
inline const Fixed operator-(const Fixed& first, const float& second)
{
// Your definition here.
}
with friend operators you can have your class on either side of the operator it self.
In general, free function operators for arithmetic operations are better than implementing member functions. The main reason is the problem you are facing now. The compiler will treat the left and right sides differently. Note that while strict OO followers will consider only those methods inside the class curly braces part of its interface, but it has been argued by experts that not to be the case in C++.
If the free function operator requires access to private members, make the operator friend. After all if it is provided in the same header file (following Sutter's rationale above) then it is part of the class.
If you really want to avoid it and don't mind making your code less idiomatic (and thus less maintainable) you can provide a public method that does the real work and dispatch to that method from the operator.
class Fixed {
private:
Fixed();
Fixed( double d ); // implicit conversion to Fixed from double
Fixed substract( Fixed const & rhs ) const;
// ...
};
Fixed operator-( Fixed const & lhs, Fixed const & rhs )
{
return lhs.substract( rhs );
}
In the code above, you can substract Fixed - Fixed, Fixed - double, double - Fixed. The compiler will find the free function and implicitly convert (in the example through the double constructor) the doubles into Fixed objects.
While this is unidiomatic for arithmetic operators, it is close to the idiomatic way of proving a polymorphic dump operator. So while not being the most natural solution it won't be the most surprising code around either
// idiomatic polymorphic dump operator
class Base {
public:
virtual std::ostream& dump( std::ostream & ) const;
};
std::ostream& operator<<( std::ostream& o, Base const & d )
{
return d.dump( o );
}
Related
I have been trying to solve this bug for days. I made a generic array class, from which I used generic inheritance to create a numeric array. Everything works perfect; however, I am having trouble with multiplication/scaling of the numeric array. I overloaded the operator* in the following standard way:
//Scaling operator
template <typename Type>
NumericArray<Type>& NumericArray<Type> :: operator * (const double factor) // scaling the elements
{
for (int i = 0; i < (*this).size(); i++)
{
(*this)[i] *= factor;
}
return *this;
}
Of course, due to the inherent order demanded by this implementation, I can only do multiplication in the way of array * 2. But I also want to be able to write 2 * array. So I decided to implement a friend function as follows:
template <typename Type>
NumericArray<Type> operator* (Type factor, const NumericArray<Type>& num_array)
{
return(num_array * factor);
}
The declaration of this friend function is as follows:
template <typename Type> friend NumericArray<Type> operator * (double factor, const NumericArray<Type>& num_array);
But when I try to write 2 * array in main(), I get the error message:
Severity Code Description Project File Line
Error C2678 binary '*': no operator found which takes a left-hand operand of type 'const NumericArray' (or there is no acceptable conversion)
The error makes me think that main() doesn't even recognize that the friend function exists. I have used friend functions a few times before, but I am pretty new to templates. I've been told that templates and generic programming in general has some weird quirky necessities, which may cause unforeseen circumstances.
For anyone who wants to see the full program, see the dropbox link:
https://www.dropbox.com/sh/86c5o702vkjyrwx/AAB-Pnpl_jPR_GT4qiPYb8LTa?dl=0
Thanks again for your help:)
NumericArray<Type> in the friend function is const, it can not call a not const function--- NumericArray<Type>& NumericArray<Type> :: operator * (const double factor)
NumericArray<Type>& operator * (const double factor)
This is a non const member function. This means it may mutate the object it's called on.
Your parameter in the free operator function (which doesn't need to be a friend if calling the public operator above) is
const NumericArray<Type>&
and therefore const qualified.
To solve it, you need to change the member function to be callable on const qualified instances (given that it really does not mutate it's instance, which it shouldn't)(*):
NumericArray<Type>& operator * (const double factor) const
(*) Yours is mutating it's instance, this is counter intuitive:
c = a * b;
You don't want a to be changed after that, in general.
As Nicky C suggests in his answer, the best approach here is probably to have an operator*= as (non const, public) member function, which is doing what currently your operator* seems to be doing.
Then you add two free operator* functions which use the operator*= to implement their behaviour.
So no need for friends in this case.
I am not sure whether I want to explain everything since it can be complicated if we go deep. But in short:
You've mixed up the meanings and implementations of *= and *.
The errors involve a lot of things: template instantiation, const-correctness, overload resolution...
So, let's just look at the idiomatic way to do so.
Step 1: Write a member operator *=.
template <typename Type>
class NumericArray
{
//...
NumericArray& operator *= (const Type factor)
{
[[ Code that scales up every element, i.e. your for-loop ]]
return *this;
}
//...
}
Step 2: Write a pair of non-member non-friend operator *
template <typename Type>
NumericArray<Type> operator * (const NumericArray<Type>& num_array, const Type factor)
{
NumericArray<Type> new_num_array = num_array; // Copy construct
new_num_array *= factor; // Scale up
return new_num_array;
}
// And similarly for factor*num_array
I've read the section 13.5 of the working draft N3797 and I've one question. Let complex be a class type which represents complex numbers. We can define the following operator function:
complex operator+(double d, complex c)
{
return *new complex(d+c.get_real(),c.get_imagine());
}
But how this operator function can be implements as a complex member function? Or must I to declare this operator function in every module which I've intend to use them?
There are two ways to define a binary operator overload, such as the binary + operator, between two types.
As a member function.
When you define it as member function, the LHS of the operator is an instance of the class. The RHS of the operator is the argument to the function. That's why when you define it as member function, it can only have one argument.
As a free function.
These functions must have two arguments. The first argument is the LHS of the operator and the second argument is the RHS of the operator.
Since double is not a class, you have to define operator+ overload between double as LHS and complex as RHS as a free function, with double const& or double as the first argument type and complex const& or complex as the second argument type.
What you're looking for is this:
inline complex operator +(double d, const complex& c)
{
return complex(d+c.get_real(), c.get_imagine());
}
This cannot be a member function if you want the operator to handle a left-side of the operator as a double. It must be a free function, possibly friended if access to anything besides the public interface of complex is needed.
If you want the right side of the add-op to be a double, a member function can be crafted:
complex operator +(double d) const
{
return complex(d+get_real(), get_imagine());
}
Note this is assuming this definition is within the body of the complex class definition. But in the interest of clarity I would recommend both be inline free functions.
Implicit Construction
Lined up with the usual suspects, what you're at-least-appearing to try to do is generally done with an implicit conversion constructor and a general free-function. By providing this:
complex(double d) : real(d), imagine()
{
}
in the class definition a double can implicitly construct a temporary complex where needed. This allows this:
inline complex operator +(const complex& lhs, const complex& rhs)
{
return complex(lhs.get_real() + rhs.get_real(),
lhs.get_imagine() + rhs.get_imagine());
}
to be used as a general solution to all sensible manifestations of what you appear to want.
In C++, operator overloading requires class types. You cannot overload the + operator for the basic type double.
Also, except in certain circumstances (short-lived programs or throwaway code), the pointer resulting from a call to the new operator should be captured, so that it can be later released with delete, preventing a situation known as a memory leak.
For it to be a member, the first parameter must be of the class type(though it is not explicitly specified). But you are sending a double as first argument. If you need this to work either make it friend function or just non-member function which can work only using public interface of the Complex class. And as others pointed out, you are leaking memory.
If I want to overload operator +, which prototype is correct?
D operator+(const D& lhs, const D& rhs);
then declare it as a friend function of D.
D operator+(const D& s);
Then declare it as a member function of D.
The first is correct, the second is plain wrong. You can improve the second by writing this
D operator+(const D& s) const;
but it's still wrong. The reason is that the compiler will apply different rules to the left and right hand sides of your + operator in the second version. For instance given this code
class C
{
};
class D
{
public:
D(const C&);
};
C c;
D d;
d = d + c; // legal with both versions
d = c + d; // not legal with the second version
The difference is because the compiler will create a temporary D object from a C object for a method or function argument but it won't do it to make a method call on the temporary object.
In short the first version treats the left hand side and right hand side equally and so agrees better with the coders expectations.
The second one should be
D operator+(const D& s) const;
Then either is good.
As to the first needing to be a friend: only if it really needs access to anything private. Normally you can implement it in terms of the public interface, commonly with the corresponding operator+=:
D operator+(D lhs, const D& rhs) { //copy left-hand side
return lhs += rhs; //add the right-hand side and return by value
}
I would advice you to follow a third path: Implement operator+= as a member function, and then implement operator+ in terms of the previous like:
D operator+=( D lhs, D const & rhs ) {
lhs += rhs;
return lhs;
}
The advantage of the third way is that with basically the same code you provide both + and +=, and you get to implement operator+ as a free function which is an advantage from the point of view of symmetry, if your class has implicit conversions, it will allow d + t and t + d for any object d of type D and any other object t of type implicitly convertible to D. The member function version will only apply conversions to the right hand side, which means that d + t will be allowed, but not t + d.
[self publicity warning] You can read a longer explanation on this particular issue here
Go with the first one. However, if it needs to access private members,only then make it friend, otherwise make it non-friend function.
I think both are correct. But one thing you missed (that may or may not apply), is that if the left side value can be something other than D (say an integer or something) then option 1 works for that e.g.
D operator+(int lhs, const D& rhs);
Then you can do something like:
D d1;
D d2 = 5 + d1;
You only need to declare a function as a friend of a class if you plan to access private variables of the class through this function. In the first prototype you do not need to declare the function as a friend since you are passing in all the values you plan to use. In the second prototype you can declare the function a friend since you will need to access one more variable, but it is better practice and easier to just declare the function as a member.
Both methods are almost correct. It's just two ways of doing almost the same. But when you need to apply the binary operator to other types other than D (for example int+D) you need to use the second one.
The option 1 does not even have to be a friend if it does not need access to the private members.
The option 2 have to be fixed a little. You are missing D::.
D D::operator+(const D& s) const {
}
The principle of least surprise says that your overload should behave
more or less like the built-in operators. The usual solution here is
not to implement operator+ at all, but to implement:
D& operator+=( D const& rhs );
as a member, and then derive from something like:
template<typename T>
class ArithmeticOperators
{
friend T operator+( T const& lhs, T const& rhs )
{
T result( lhs );
result += rhs;
return result;
}
// Same thing for all of the other binary operators...
};
This way, you don't have to rewrite the same thing every time you define
a class which overloads the arithmetic operators, and you're guaranteed
that the semantics of + and += correspond.
(The friend in the above is simply to allow you to put the function,
along with its implementation, in the class itself, where ADL will find
it.)
Both are correct (after fixing the const correctness problem others pointed out), but I recommend the member operator. It can be overridden with polymorphic behavior if virtual, have better cohesion with the class and as a result it is easier to maintain and to document. Try to avoid friend functions if you can.
As for the "derived = base + derived" case, I recommend not mixing value semantics operators and polymorphism, it can have unforeseen consequences due to various implicit conversion sequences and object slicing. That example might be equivalent to derived = Derived(base) + derived, but it can be derived = Derived(base + Base(derived)) as well if base has operator +.
Use only explicit conversion and casting, and you will not encounter any mysterious strange behavior. And think twice before you implement operators for a polymorphic class.
The first one has a different behavior if D has implicit constructors.
Consider
struct D
{
D(int);
};
D operator+(const D&, const D&);
Then you can do 1 + d and d + 1, which you cannot do with the member operator+ (the lhs must be a D, and no conversion shall take place).
In some books and often around the internet I see recommendations like "operator== should be declared as friend".
How should I understand when an operator must be declared as friend and when it should be declared as member? What are the operators that will most often need to be declared as friends besides == and <<?
This really depends on whether a class is going to be on the left- or right-hand side of the call to operator== (or other operator). If a class is going to be on the right-hand side of the expression—and does not provide an implicit conversion to a type that can be compared with the left-hand side—you need to implement operator== as a separate function or as a friend of the class. If the operator needs to access private class data, it must be declared as a friend.
For example,
class Message {
std::string content;
public:
Message(const std::string& str);
bool operator==(const std::string& rhs) const;
};
allows you to compare a message to a string
Message message("Test");
std::string msg("Test");
if (message == msg) {
// do stuff...
}
but not the other way around
if (msg == message) { // this won't compile
You need to declare a friend operator== inside the class
class Message {
std::string content;
public:
Message(const std::string& str);
bool operator==(const std::string& rhs) const;
friend bool operator==(const std::string& lhs, const Message& rhs);
};
or declare an implicit conversion operator to the appropriate type
class Message {
std::string content;
public:
Message(const std::string& str);
bool operator==(const std::string& rhs) const;
operator std::string() const;
};
or declare a separate function, which doesn't need to be a friend if it doesn't access private class data
bool operator==(const std::string& lhs, const Message& rhs);
When you have your operators outside the class, both parameters can participate in implicit type conversions (whereas with operators being defined in the class body, only the right-hand operands can). Generally, that's a benefit for all the classic binary operators (i.e. ==,!=, +, -, <<, ... ).
Of course you should only declare operators friends of your class if you need to and not if they compute their result solely based on public members of the class.
Generally, only operators which are implemented as free functions that genuinely need to access to private or protected data of the class that they operate on should be declared as friends, otherwise they should just be non-friend non-member functions.
Generally, the only operators that I implement as member functions are those that are fundamentally asymmetric and where the operands don't have equivalent roles. The ones that I tend to implement as members are those required to be members: simple assignment, (), [] and -> together with compound assignment operators, unary operators and perhaps some overloads of << and >> for classes that are themselves stream or stream-like classes. I never overload &&, || or ,.
All other operators I tend to implement as free functions, preferably using the public interface of the classes which they operate on, falling back to being friends only where necessary.
Keeping operators such as !=, ==, <, +, /, etc as non-member functions enables identical treatment of the left and right operands with respect to implicit conversion sequences which helps to reduce the number of surprising asymmetries.
No one has mentioned hidden friends idiom which I suspect is what the books mean.
Long version: https://www.justsoftwaresolutions.co.uk/cplusplus/hidden-friends.html
Short version:
Operators are found via ADL (argument dependent lookup) most of the time. This is how an operator== defined for std::string in std is found when you are not in namespace std.
One of the problems, common for operators is a gigantic overload set. You can often see this in error messages if you try to use operator<< for something that is not printable.
So - if you declare operator== in the namespace containing the class directly, it will work but it will also participate in all of the overload resolutions in that namespace which is going to slow down your compilation and give you more noise in the errors.
Introducing hidden friends:
struct X {
friend bool operator==(const X& x, const X& y) {...}
};
This operator== will only be considered for overload resolution if one of the operands has type X. In all other cases it will not be seen, so your compilation will be faster and your error messages better.
Same goes for all two operand operators, like operator<< and also other functions intended for ADL, like swap.
I always define my operators like this and it's considered a good practise by quite a few people nowadays.
The only downside is - there is no very good way to define it out of line. You might want to consider dispatching to some private function.
Or you can do this: https://godbolt.org/z/hMarb4 - but it means that at least in one cpp file the operator== will participate in normal lookup.
Why it is not allowed to overload "=" using friend function?
I have written a small program but it is giving error.
class comp
{
int real;
int imaginary;
public:
comp(){real=0; imaginary=0;}
void show(){cout << "Real="<<real<<" Imaginary="<<imaginary<<endl;}
void set(int i,int j){real=i;imaginary=j;}
friend comp operator=(comp &op1,const comp &op2);
};
comp operator=(comp &op1,const comp &op2)
{
op1.imaginary=op2.imaginary;
op1.real=op2.real;
return op1;
}
int main()
{
comp a,b;
a.set(10,20);
b=a;
b.show();
return 0;
}
The compilation gives the following error :-
[root#dogmatix stackoverflow]# g++ prog4.cpp
prog4.cpp:11: error: ‘comp operator=(comp&, const comp&)’ must be a nonstatic member function
prog4.cpp:14: error: ‘comp operator=(comp&, const comp&)’ must be a nonstatic member function
prog4.cpp: In function ‘int main()’:
prog4.cpp:25: error: ambiguous overload for ‘operator=’ in ‘b = a’
prog4.cpp:4: note: candidates are: comp& comp::operator=(const comp&)
prog4.cpp:14: note: comp operator=(comp&, const comp&)
Because if you do not declare it as a class member compiler will make one up for you and it will introduce ambiguity.
The assignment operator is explicitly required to be a class member operator. That is a sufficient reason for the compiler to fail to compile your code. Assignment is one of the special member functions defined in the standard (like the copy constructor) that will be generated by the compiler if you do not provide your own.
Unlike other operations that can be understood as external to the left hand side operator, the assignment is an operation that is semantically bound to the left hand side: modify this instance to be equal to the right hand side instance (by some definition of equal), so it makes sense to have it as an operation of the class and not an external operation. On the other hand, other operators as addition are not bound to a particular instance: is a+b an operation of a or b or none of them? -- a and b are used in the operation, but the operation acts on the result value that is returned.
That approach is actually recommended and used: define operator+= (that applies to the instance) as a member function, and then implement operator+ as a free function that operates on the result:
struct example {
example& operator+=( const example& rhs );
};
example operator+( const example& lhs, const example& rhs ) {
example ret( lhs );
ret += rhs;
return ret;
}
// usually implemented as:
// example operator+( example lhs, const example& rhs ) {
// return lhs += rhs; // note that lhs is actually a copy, not the real lhs
//}
Assignment(=) operator is a special operator that will be provided by the constructor to the class when programmer has not provided(overloaded) as member of the class.(like copy constructor).
When programmer is overloading = operator using friend function, two = operations will exists:
1) compiler is providing = operator
2) programmer is providing(overloading) = operator by friend function.
Then simply ambiguity will be created and compiler will gives error. Its compilation error.
There is no good reason for that, I think Stepanov proposed that there should be a free operator= and many good stuff can be done with that (even more than what can be done with the move assignment). I can't find the citation but Stepanov went as a far as to suggest that the constructors could be free functions http://www.stlport.org/resources/StepanovUSA.html.
There is a way around it, which is to systematically declare a template<class Other> A& operator=(Other const& t); in inside all your classes, in this way you leave the option to anyone to define a custom assignment operator.
Of course you can't do this with a class you don't have control over.
Having said that it is nowadays not that bad since we have move assignment. And in some sense conversion operators B::operator A() const{...} are almost like a custom copy assignment. Conversion operators are now usable because of explicit. However you have to have control over the second type (B), the right-hand type in assignment.
Next question is why conversion operator need to be members them selves? Again, I don't think there is a good reason.