Can we use operator overloading on non-objects? e.g adding two vector<int>. Or do I need to make a class having vector<int> and then overload the + operator.
Also, I want to know if it is possible to have 2 different types of operands in a binary operator. If yes, how?
Can we use operator overloading on non-objects?
Operators are essentially implemented as functions and can accept a similar range of types as functions do.
There are a few restrictions, in particular, it is limited by the fact that at least one argument must be a class or enum (user or library type).
In addition, there are some operators that have to be implemented as member functions, so they will be associated with a class, but many can be declared and defined outside of a class.
The exact number of arguments is determined by the operator being implemented. Unary operators accept 1 argument, binary operators accept 2 arguments.
Generally, the advice is to offer behaviour similar to the canonical forms, but the language itself does not limit your implementation to just that behaviour.
Also, I want to know if it is possible to have 2 different types of operands in a binary operator. If yes, how?
Yes. Again, just as functions do.
Can we use operator overloading on non-objects? e.g adding two vector.
I think you meant to ask whether it's possible to use operator overloading outside of a class definition. And yes, it definitely is possible as already stated by other people here. Here's a simple example of overloading the '+' operator for a custom 'MyClass' type:
MyClass operator+(const MyClass& a, const MyClass& b)
{
return MyClass(a.value + b.value);
}
However, there is a reason why std::vector doesn't have overloads for arithmetic operators as the result is ambiguous. Do you want '+' to link two vectors together or should the components be added? How do you handle vectors which differ in size? Often, containers of the STL provide special methods for these purposes and don't rely on operators when it's not clear so make sure you've checked the specification of std::vectors
You're free to implement such operators as you see fit, especially with your own types but you risk creating unintuitive behaviour and ultimately, bad code. In the case of std::vector, it might be better to write a function with a descriptive name which operates on std::vector in the way you desire:
std::vector<int> addComponents(const std::vector<int>& a, const std::vector<int>& b);
Can we use operator overloading on non-objects? e.g adding two vector[?]
The premise of your question is broken, because a vector<int> is an object.
Overload all you like.
Also, i want to know if it is possible to have 2 different types of operands in a binary operator.
Try it.
If yes, how?
By typing it.
Related
I'm new to C++ and my questions are: Why do we need to overload operators in C++ and when should we overload operators in C++, why don't we just use built-in variables to do calculations, comparison, output and input value. I just don't get it, what is the most appropriate situation where we would need to overload operators or should we always overload operators when dealing with classes?
If you look at a lot of C++ sources, you'd probably conclude
that the most frequent use of operator overloading (or
overloading in general, for that matter) is obfuscation.
Still...
First and foremost: in a number of cases, you'll have to
overload the assignment operator. The compiler will generate
one for you if you don't, and in a number of cases, the
generated one won't do what you want. (It's also frequent to
declare a private overloaded assignment, and not implement it,
in order to block assignment.)
If a class represents some sort of numerical value (e.g.
BigInteger or Decimal), then it definitely makes sense to
overload the arithmetic operators. It's a lot more readable to
write:
BigFloat
discriminant( BigFloat const& a, BigFloat const& b, BigFloat const& c )
{
return b*b - 4*a*c
}
than
BigFloat
discriminant( BigFloat const& a, BigFloat const& b, BigFloat const& c )
{
return sub(mult(b, b), mult(4, mult( a, c )));
}
In such cases, you should always overload all applicable
operators, with their natural meanings: it would be very uncool
if your type supported +, but not +=, or if it supported +
with the semantics of subtraction.
There are few legitimate extensions with regards to the
arithmetic operators: about the only one I'd find acceptable is
a string class using + (and +=) for concatenation.
(Normally, I'd expect + to be commutative, which concatenation
certainly isn't. But the convention is so well established in
languages that have built-in string types that you can hardly
avoid it.)
Types that are comparable should support == and !=, and if
there is a logical ordering, <, <=, > and >=. (On the
other hand, overloading < when there is only an arbitrary
ordering, just so you can call std::sort without an comparison
operator, is obfuscation.) Again, it's much more natural to
write a < b than isLessThan( a, b ). It's sometimes
difficult to decide: when I first started C++, I had a Set
class, based on bitmaps, and I defined < to be a strict
subset, <= a subset, etc. I don't know if I'd do this again;
the inequality operators should probably only be defined if the
relationship is transitive.
Beyond that, any time your type emulates in some way something
built in, like a pointer or an array, you will probably want to
overload the corresponding supported operators: a vector or an
array class which didn't support [] would be surprizing, as
would be a smart pointer which didn't support * and ->.
And finally, there are some standard C++ idioms which use
operator overloading:
If you define a type which can be inserted or extracted from a text stream, you do so by defining the << and >> operators.
C++ iterators are designed to look like pointers; if you want
iterators which can be used with the standard algorithms, they
should support the same operators as those of a smart pointer,
along with ++, and possibly --, and in some cases, all of
the pointer arithmetic operators (including [], which is
defined in terms of pointer arithmetic on raw pointers). This
is clearly obfuscation, and it certainly makes using the
iterators unnecessarily complicated, but it's hard to avoid if
you're using the C++ standard library.
The C++ library also makes extensive use of functional
objects, with an operator() (a function call operator).
Predicate objects have an operator() which returns a bool.
(One of the most frequent uses of predicate objects is to
implement an ordering relationship. If your class doesn't
support a logical < operator, you might want to provide
a separate functional object which defines an arbitrary order,
so that objects can still be inserted into std::set, or be
used as a key in std::map.) Arguably, this too should have
been a named function, but it's hard to imagine a good name that
would apply everywhere, and since the object does behave like
a function, it's not really too bad.
There are probably one or two other cases I've forgotten, but in
general, with regards to operator overloading, when in doubt,
don't.
This is a bit of a general question, but I have some classes that I'd like to define some binary "operations" on, and there are several different ways of doing so. For example, suppose I have a Vector class that I'd like to implement an addition operation on. On one hand, I could just overload the '+' operator, but I have read from a few sources that this isn't a very good practice (which begs one to ask why this is a language feature at all). I can see in many cases why methods are preferable to operator overloading, but vector addition is widely agreed upon and so using '+' should be very natural.
On the other hand, I could define an add() method in the class. I could just define it as a normal method and use x.add(y) to perform x + y, but it doesn't showcase itself as a binary operator so I'm not sure if this should be preferred. I could also define it as a static method, for instance Vector.add(x, y). Finally, I could also define add() as a friend function of the class, which is very (mathematically) natural but in my opinion is a bit contrary to the philosophy of OOP. I'm hoping to get a bit of insight into which methods are preferable (and why).
The usual approach is to define reflexive operators (+=, *=, etc.) as members that modify the object they are applied to, and to define non-reflexive operators (+, *, etc.) as non-members that create a copy of one of their arguments, use the corresponding reflexive operator to do the operation, and return the new object as their result.
While Java programmers believe that add functions are a good thing, they do so because Java doesn't have operator overloading. Named operations lead to really long and unreadable expressions for things that should be simple.
The advantage to defining your binary operator as a friend function (potentially as a set of overloads) is to permit the left-hand value to be other than an instance of your class. This is commonly done for stream inserters/extractors. Note that the friend status is only necessary if your operator requires access to the internals of one of its operands. It's best if the operator can work through the public interfaces of each operand, avoiding the need for friend and the resulting tighter coupling.
I've started learning C++, so I don't know in my lack of knowledge/experience why something so seemingly simple to a rookie as what I'm about to describe isn't already in the STL. To add a vector to another vector you have to type this:
v1.insert(v1.end(), v2.begin(), v2.end());
I'm wondering whether in the real world people just overload the += operator to make this less verbose, for example to the effect of
template <typename T>
void operator+=(std::vector<T> &v1, const std::vector<T> &v2) {
v1.insert(v1.end(), v2.begin(), v2.end());
}
so then you can
v1 += v2;
I also have this set up for push_back to "+=" a single element to the end. Is there some reason these things should not be done or are specifically avoided by people who are proficient in C++?
This is actually a case where I would like to see this functionality in the form of an overload of append(). operator+= is kinda ambiguous, do you mean to add the elements of each vector to each other? Or you mean to append?
However, like I said, I would have welcomed: v1.append(v2); It is clear and simple, I don't know why it isn't there.
I think the main reason is that the semantics of += aren't obvious. There's the meaning that you have here, but there's also an equally valid meaning, which is element-wise addition of each element of equal-sized vectors. Due to this ambiguity I assume they decided it was better to rely on the user to call insert diretly.
Operators should be overloaded only when you are not changing the meaning of those operators.*
What that means is, for example, if there is no mathematical definition of the product of two objects, don't overload the multiplication operator for those objects. If there was a mathematical correspondence, operators overloading can make a class more convenient to use by allowing equations to be expressed in the form a*b + c rather than the more verbose (a.multiply(b)).add(c) Where addition and multiplication operators are used, addition and multiplication should be the intent. Any other meaning is more than likely to confuse others. Some other types where overloading operators is acceptable (and, in my opinion, preferable) are smart pointers, iterators, complex numbers, vectors, and bignums.
This follows from one of the design goals of C++, that it should be possible to define classes that are as easy to use as built in types. Of course there are operators you can define on classes which are not mathematical concepts either. You may wish to overload the == and != operators instead of writing an isEqual method, and might want to overload = because the compiler's default assignment operator is not what you want.
On the other hand, overloading an operator to do something unexpected, like defining ^ to translate a string to Japanese, is obscure and dangerous. Your fellow programmers will not be happy to find out that what looked like an exclusive or comparison was actually something very different. The solution then is to write your classes to make it easy to write clear and maintainable code, whether that means using operator overloading or avoiding it.
Adding two vectors is too ambiguous to warrent defining an operator. As others have shown, many people have different ideas of what this means, whereas for a string it is universally understood that adding two strings together means concatenation. In your example, it isn't entirely clear whether you want to do a component wise add on all the elements, add an element to the end, or concat two vectors together. Although it may be more concise to do it that way, using operator overloading to create your own programming language isn't the best way to go.
*Yes, I know Stroustrup overloaded << and >> to do stream operations rather than bitshifts. But those weren't used often compared to arithmetic and pointer operators in the first place, and it could be argued that now that everyone knows how to use cout, it's generally understood that << and >> are the inserter and extractor operators. (He originally tried to use just < and > for input and output, but the meaning of those operators was so ingrained in everyone's minds that the code was unreadable.)
In addition to what others mentioned about this syntax not being intuitive and therefore error prone, it also goes against a good design rule making general algorithms applied to various containers free functions, and container specific algorithms -- member functions. Most containers follow this rule, except std::string, which got a lot of flack from Herb Sutter for its monolithic design.
When overloading operators, is it necessary to overload >= <= and !=?
It seems like it would be smart for c++ to call !operator= for !=, !> for operator<= and !< for operator>=.
Is that the case, or is it necessary to overload every function?
Boost operators might be what you are looking for. These will derive most of your operators based on a few fundamental ones.
That C++ does not provide this automatically makes sense, as one could give totally different meanings to < and >, for example (although it would often be a bad idea).
I am going to take a minority viewpoint here. If you already use boost then using boost operators is not that big of a deal. It may be the correct and tested way to do things but adding boost dependency just for the operators is an overkill.
It is possible to write complex C++ programs without boost (which I personally find aesthetically unpleasant) and so to Keep It Simple (Stupid), to answer OP's question, if you overload operator ==, you should also overload operator !=. Same is true for <, >, ++ etc.
Yes, it is necessary, if you want all of them to work the way you want them to work.
C++ does not force any specific semantics on most of the overloadable operators. The only thing that is fixed is the general syntax for the operator (including being unary or binary and things like precedence and associativity). This immediately means that the actual functionality that you implement in your overload can be absolutely arbitrary. In general case there might not be any meaningful connection between what operator == does and what operator != does. Operator == might write data to a file, while operator != might sort an array.
While overloading operators in such an arbitrary fashion is certainly not a good programming practice, the C++ language cannot assume anything. So, no, it cannot and will not automatically use ! == combination in place of !=, or ! > combination in place of <=.
No, you only need to overload operator == and operator <, the standard library will take care of the rest :)
(EDIT: see using namespace std::rel_ops ;)
Yes it is necessary to overload whichever operators you want to be used as you define them - C++ will not make the decision you describe above; however, keep in mind that if the reason you are overloading is to sort your class, than you only need to override the operators used by the sort routine. In the case of the RTL sort algorithm you only need to override < and =.
Yes! They are each technically different operators. C++ compilers are not inherently inference engines, they are parsers/compilers. They will only do as much as you say to do.
http://www.parashift.com/c++-faq-lite/operator-overloading.html, http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B
There are a few shortcuts you can use, such as CRTP to get them automatically injected (see the various Compare classes) into your class.
C++ does not, as a language, define any operator in terms of any other overloaded operator. Just because you have operator+, doesn't mean you get operator+= for free (unlike Ruby and Scala). Just because you have operator < and == doesn't mean you get <= for free. Just because you have operator == doesn't mean you get != for free (unlike Ruby and Scala). Just because you have unary operator * (unary) doesn't mean you get operator -> for free.
std::relops (if imported correctly) and provide default definitions, and Boost provides some mix-ins that define all of the comparison operators in terms of < and ==.
You can use overloading to use user defined names.
Operator overloading means using the same operator to do perform operation on different items which are not in that category. Function overloading means using the same name of function but different arguments, so as to overcome the overhead when the same function is called during looping.
Why can some operators only be overloaded as member functions, other as non-member "free" functions and the rest of them as both?
What is the rationale behind those?
How to remember which operators can be overloaded as what (member, free, or both)?
The question lists three classes of operators. Putting them together on a list helps, I think, with understanding why a few operators are restricted in where they can be overloaded:
Operators which have to be overloaded as members. These are fairly few:
The assignment operator=(). Allowing non-member assignments seems to open the door for operators hijacking assignments, e.g., by overloading for different versions of const qualifications. Given that assignment operators are rather fundamental that seems to be undesirable.
The function call operator()(). The function call and overloading rules are sufficiently complicated as is. It seems ill-advised to complicate the rules further by allowing non-member function call operators.
The subscript operator[](). Using interesting index types it seems that could interfere with accesses to operators. Although there is little danger of hijacking overloads, there doesn't seem to be much gain but interesting potential to write highly non-obvious code.
The class member access operator->(). Off-hand I can't see any bad abuse of overloading this operator a non-member. On the other hand, I also can't see any. Also, the class member access operator has rather special rules and playing with potential overloads interfering with these seems an unnecessary complication.
Although it is conceivable to overload each of these members are a non-member (especially the subscript operator which is works on arrays/pointers and these can be on either side of the call) it seems surprising if, e.g., an assignment could be hijacked by a non-member overload which which is a better match than one of the member assignments. These operators are also rather asymmetric: you generally wouldn't want to support conversion on both sides of an expression involving these operators.
That said, e.g., for a lambda expression library it would be nice if it were possible to overload all of these operators and I don't think there is an inherent technical reason to preventing these operators from being overloadable.
Operators which have to be overloaded as non-member functions.
The user-defined literal operator"" name()
This operator is somewhat of an odd-ball and, arguably not really really an operator. In any case, there is no object to call this member on for which members could be defined: the left argument of user-defined literals are always built-in types.
Not mentioned in the question but there are also operator which can't be overloaded at all:
The member selector .
The pointer-to-member object access operator .*
The scope operator ::
The ternary operator ?:
These four operators were considered to be too fundamental to be meddled with at all. Although there was a proposal to allow overloading operator.() at some point there isn't strong support doing so (the main use case would be smart references). Although there are certainly some contexts imaginable where it would be nice to overload these operators, too.
Operators which can be overloaded either as members or as non-members. This is the bulk of the operators:
The pre- and post-increment/-decrement operator++(), operator--(), operator++(int), operator--(int)
The [unary] dereference operator*()
The [unary] address-of operator&()
The [unary] signs operator+(), operator-()
The logical negation operator!() (or operator not())
The bitwise inversion operator~() (or operator compl())
The comparisons operator==(), operator!=(), operator<(), operator>(), operator<=(), and operator>()
The [binary] arithmetic operator+(), operator-(), operator*(), operator/(), operator%()
The [binary] bitwise operator&() (or operator bitand()), operator|() (or operator bit_or()), operator^() (or operator xor())
The bitwise shift operator<<() and operator>>()
The logic operator||() (or operator or()) and operator&&() (or operator and())
The operation/assignment operator#=() (for # being a suitable operator symbol()
The sequence operator,() (for which overloading actually kills the sequence property!)
The pointer pointer-to-member access operator->*()
The memory management operator new(), operator new[](), operator new[](), and operator delete[]()
The operators which can be overloaded either as members or as non-members are not as necessary for fundamental object maintenance as the other operators. That is not to say that they are not important. In fact, this list contains a few operators where it is rather questionable whether they should be overloadable (e. g., the address-of operator&() or the operators which normally cause sequencing, i. e., operator,(), operator||(), and operator&&().
Of course, the C++ standard doesn't give a rationale on why things are done the way they are done (and there are also no records of the early days when these decisions where made). The best rationale can probably be found in "Design and Evolution of C++" by Bjarne Stroustrup. I recall that the operators were discussed there but there doesn't seem to be an electronic version available.
Overall, I don't think there are really strong reasons for the restrictions other than potential complication which was mostly not considered worth the effort. I would, however, doubt that the restrictions are likely to be lifted as the interactions with existing software are bound to change the meaning of some program in unpredictable ways.
The rationale is that it would not make sense for them to be non-members, as the thing on the left-hand side of the operator must be a class instance.
For example, assuming a class A
A a1;
..
a1 = 42;
The last statement is really a call like this:
a1.operator=(42);
It would not make sense for the thing on the LHS of the . not to be an instance of A, and so the function must be a member.
Because you can't modify the semantics of primitive types. It wouldn't make sense to define how operator= works on an int, how to deference a pointer, or how an array access works.
Here is one example:
When you are overloading the << operator for a class T the signature will be:
std::ostream operator<<(std::ostream& os, T& objT )
where the implementation needs to be
{
//write objT to the os
return os;
}
For the << operator the first argument needs to be the ostream object and the second argument your class T object.
If you try to define operator<< as a member function you will not be allowed to define it as std::ostream operator<<(std::ostream& os, T& objT).
This is because binary operator member functions can only take one argument and the invoking object is implicitly passed in as the first argument using this.
If you use the std::ostream operator<<(std::ostream& os) signature as a member function you will actually end up with a member function std::ostream operator<<(this, std::ostream& os) which will not do what you want.
Therefore you need a operator that is not a member function and can access member data (if your class T has private data you want to stream, operator<< needs to be a friend of class T).