85

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?

7
  • 7
    That depends on how narrowly you define the term "operator".
    – molbdnilo
    Jun 30, 2020 at 12:47
  • 12
    This is not forced by the standard - for example you can implement += to return void, but this is not recommended. Also function call operators can return void and this is valid Jun 30, 2020 at 12:47
  • 1
    Hmm. I have a hunch that scope resolution operator :: doesn't return anything, but I'd have to consult standard to make sure. Jun 30, 2020 at 12:47
  • 2
    Is the context of the question for C++ provided types only, or does it also include user-defined types?
    – Eljay
    Jun 30, 2020 at 13:04
  • @Eljay Only the C++ provided types. Jun 30, 2020 at 13:06

12 Answers 12

119

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;
7
  • 14
    I like your answer, it made me think of the question differently. delete, delete[], throw, (void)x; cast, left side of , operator, right side of , operator that yields a void, a ?: ternary that uses a throw for one of the arms, dfri's operator void() (which would be user defined), 眠りネロク's void operator()() (which would be user defined).
    – Eljay
    Jun 30, 2020 at 13:14
  • 10
    It's also confusing that the delete operator destroys the object and then calls operator delete. Ergo, the delete operator and operator delete are separate things :( stackoverflow.com/a/8918942/845092 Jul 1, 2020 at 22:18
  • 7
    Not sure why you cite the delete-functions when talking about the delete-operator. But whatever. Jul 2, 2020 at 7:56
  • 4
    @MooingDuck The delete expression destroys the object, and then calls operator delete. Jul 2, 2020 at 13:17
  • Does the delete count as an operator through, I thought an object is something that acts on an object that is passed?? Delete does not need any object to be passed or created for it to work..... Just like printf..... Jul 10, 2020 at 16:31
83

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->.

18
  • Funnily enough, there is actually no constraint on overloaded operators return value. So, operators can return whatever you want. en.cppreference.com/w/cpp/language/operators
    – bracco23
    Jul 1, 2020 at 9:27
  • 5
    @braccor23 operator-> is a bit special and needs to return either a pointer or an object which has an operator->, not sure if there are other exceptions Jul 1, 2020 at 9:38
  • 1
    Yes, that's the only constraint. Not even bool for comparison operators. That looks really weird.
    – bracco23
    Jul 1, 2020 at 9:41
  • 9
    @idclev463035818: A perhaps more useful example can be Expression Templates. For example, you can make a matrix library where operator*(Matrix const& left, Matrix const& right) returns not Matrix but instead MatrixMul, so that if it is then fed into operator+(Matrix const& left, MatrixMul const& right) the operation can be a fused multiply-add which is more efficient than first multiplying then adding. Jul 1, 2020 at 10:44
  • 1
    @DarrelHoffman When << and >> are overloaded for I/O operations, they're expected to return the stream so that you can cascade them: stream << foo << bar;
    – Barmar
    Jul 1, 2020 at 14:18
35

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.

0
21

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.

10
  • 14
    @idclev463035818: It's the term return I have an issue with. The only thing in C++ that returns something is a function. Expressions evaluate to something.
    – Bathsheba
    Jun 30, 2020 at 12:51
  • 7
    operators of class types are methods that return something Jun 30, 2020 at 12:51
  • 4
    This is an important point. Sloppy terminology leads to confusion. +1. Jun 30, 2020 at 13:18
  • 3
    @supercat — your comment maligns a bunch of hardworking people, including me. Those of us who wrote the standard never expected compiler writers to fill in details by polling other compilers, present or past. The goal of the standard was and is to clearly define the syntax and semantics of the C++ programming language. Yes, the result isn’t perfect; there are many issues addressed in the latest standard that weren’t addressed in earlier versions. That comes from experience, recognizing complications that simply weren’t seen at the time. Jul 1, 2020 at 2:33
  • 3
    @Peter-ReinstateMonica — here’s a stronger version. The expression I++ does not return a value. If the type of i is a user-defined type, that expression is implemented as operator++, which is a function that returns a value. You call that “syntactic sugar”; I call that a distinction that has important consequences. Jul 1, 2020 at 11:15
13

You can actually define a function call operator to return nothing. For example:

struct Task {
   void operator()() const;
};
2
  • 17
    You can define almost any operator to return nothing (and face the wrath of angry mob that will have to maintain that code) Jun 30, 2020 at 12:47
  • 7
    @Yksisarvinen but at least this one is potentially useful. Jul 1, 2020 at 21:48
12

operator void(): user defined conversion function to void

You may define the peculiar operator void() conversion function, where the compiler will even warn you that the T to void conversion function will never be used:

#include <iostream>

struct Foo {
    operator void() { std::cout << "Foo::operator void()!"; }
    // warning: conversion function converting 'Foo' to 
    //          'void' will never be used
};
    
int main() {
    Foo f;
    (void)f;            // nothing
    f.operator void();  // Foo::operator void()!
}

as governed by [class.conv.fct]/1

[...] A conversion function is never used to convert a (possibly cv-qualified) object to the (possibly cv-qualified) same object type (or a reference to it), to a (possibly cv-qualified) base class of that type (or a reference to it), or to (possibly cv-qualified) void.117

(117) These conversions are considered as standard conversions for the purposes of overload resolution ([over.best.ics], [over.ics.ref]) and therefore initialization ([dcl.init]) and explicit casts. A conversion to void does not invoke any conversion function ([expr.static.cast]). Even though never directly called to perform a conversion, such conversion functions can be declared and can potentially be reached through a call to a virtual conversion function in a base class.

Whilst, however, as is shown above, you can still invoke it using the explicit .operator void() syntax.

4

I'm assuming you're talking about operator functions and not operators as a syntactic unit of the language.

If you overload operators on any type, you may actually return whatever you want.

This also makes a lot of sense, because operations like * or () may sometimes very intuitively not return their input type. Imagine multiplying a complex number type with a real number type. Or an operator that returns an element from a collection.

You may also overload the ++ and -- operators to not return anything thus removing the extremely error-prone mixing of side-effect and expression value that the standard version has.

4

The operators defined (builtin) by the language are tokens used to perform different kinds of computations:

  • arithmetic (+,-,*,/)
  • increment/decrement (++,--)
  • assignment (=,+=,-=,*=,/=,%=,>>=,<<=,&=,^=,|=)
  • logic (!,&&,||)
  • relational (==,!=,>,<,>=,<=)
  • conditional ?
  • comma

and so on. The list can be very extensive.

In language references like this one or this one, these are not necessarily referenced as returning something, just performing an arithmetic or logic operation, a comparison by which means a variable may be modified, etc.

Since this operation results in some value, it may be interpreted as been "returned" by the operator, but it is different from a function return value.

The overloaded operators, on the other hand, can be defined with a return value of some type, even that can be void, so, no, not all operators return some value in C++.

2

No. Consider these two examples here:

int multiply (int a, int b) {
   return a*b;
}

void multiply_void(int a, int b) {
   cout << a*b;
//or cout << multiply(a,b);
}

First function will return an integer value which can be used by another function. The value is returned and stored in memory to be used when necessary. If not, it is not visible to human & just sits happily in the memory.

Second function will output to the default output device(usually console). The value returned by the multiplication operator is passed to an output device. The function multiply_void does not return an actual value.

0

Operators on their own do not necessarily return anything. Function calls return values. Operators can result in values. Operators can sometimes invoke functions. Examples include:

• The function call operator.

• An overloaded operator that gets transformed into a function call.

• operator new, which is invoked as part of a new-expression, is a function call.

My only purpose in mentioning function calls is to clarify the result vs. return. Based on looking at all 126 instances of “return” and words derived from it in [expr], the section seems to carefully use the word return to refer to:

• the result of a function call

• aspects of control flow related to coroutines

OK, that’s enough pedantry on result vs. return.

0

C++ Operators return something or not is depends upon how you used them. Built-In C++ operators return some value until and unless enforced to return void.

-1

All operators return something. They are called operators because they operate something , therefore they will return something. Those Operators who do not return something cant be called operators. Either they will return some value or return True or False depending upon the situation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.