Do all C++ operators return something?
All C++ operators that I have worked with return something, for example the +
operator returns the result of the addition.
Do all C++ operators return something, or are there some C++ operators that do not return anything?
Solution 1:
No, not all operators return something.
Although they are probably not exactly what you are thinking about, note that the delete
and delete[]
C++ 'keywords' are actually operators; and they are defined as having the void
return type - which means they evaluate to nothing (which is not 'something').
From cppreference:
void operator delete ( void* ptr ) noexcept; void operator delete[]( void* ptr ) noexcept;
Solution 2:
Operators of custom types can be overloaded to do the most weirdest things.
for example the + operator returns the result of the addition.
Not necessarily:
#include <iostream>
struct foo {
int value = 0;
void operator+(int x) {
value += x;
}
};
int main () {
foo f;
f + 3;
}
Here operator+
adds the left hand side to the value
member, and its return type is void. This is a made-up example, but, in general, not returning something from a custom operator is not unusual.
The only operator that can be overloaded and that has the requirement of returning something, that I am aware of, is operator->
. It must either return a raw pointer or an object that has an operator->
.
Solution 3:
To nitpick, operators don't return anything. They are just lexical elements that we use to create expressions in the language. Now, expressions have types and may evaluate to values, and I assume this is what you mean by operators "returning things".
And, well, yes. There are C++ expressions with type void
(and consequentially don't evaluate to any value). Some are obvious, others less so. A nice example would be
throw std::runtime_error()
throw
is an expression under the C++ grammar. You can use it in other expressions, for instance in the conditional expression
return goodStatus() ? getValue() : throw std::runtime_error();
And the type of a throw expression, is void
. Obviously since this just causes execution to rapidly go elsewhere, the expression has no value.
Solution 4:
None of the built-in C++ operators return something. Overloaded C++ operators return something insofar that the operator notation is a syntactic sugar for a function call.
Rather, operators all evaluate to something. That something has a well-defined value as well as a type. Even the function call operator void operator()(/*params*/)
is a void
type.
For example, +'a'
is an int
type with the value of 'a'
encoded on your platform.
If your question is "Can C++ operators have a void
return type?" then the answer is most certainly yes.
Solution 5:
You can actually define a function call operator to return nothing. For example:
struct Task {
void operator()() const;
};