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?
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;
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->.
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.
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.
You can actually define a function call operator to return nothing. For example:
struct Task {
void operator()() const;
};
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.
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++.
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.
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.
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.
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.
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.
In C++, I can write something like:
shared_ptr<A> a_sp = someFunctionReturningSharedPtr();
if (a_sp) {
cout << a_sp->someData << endl;
} else {
cout << "Shared Pointer is NULL << endl;
}
Why does if (a_sp) check work correctly? a_sp is not a boolean, but how is it checked for true or false? How does the if condition know to check the result of a_sp.get() function? Or if it does not, how is the NULLity of the a_sp checked? Is there some function in shared_ptr defined that converts it to boolean value?
shared_ptr has an operator unspecified-bool-type() const that allows it to be used in boolean contexts. The unspecified-bool-type is typically defined as a pointer to function, or pointer to member-function, to disallow accidental matching to bool function overloads.
In C++0x the idiom is to use explicit operator bool() const;, which disallows implicit conversions (such as function calls, conversions to int for arithmetic, and so on), but still allows the shared_ptr to be converted to bool in boolean contexts.
shared_ptr has operator bool(), which returns true if it is not empty.
For example, this is Microsoft implementation of shared_ptr::operator bool(): http://msdn.microsoft.com/en-us/library/bb982901.aspx
shared_ptr::operator boolean-type - Tests if an owned resource exists.
What does the code below intended to do?
return cin==(cout<<(f(a)==f(b)?"YES":"NO"));
assume f() is a string returning function and a and b are strings as well and function's signature is
string f(string a)
Thanks in advance!
The answer is: it depends on what C++ standard you're compiling against. It boils down to the conversion functions in std::basic_ios
C++03
Here, we have operator void*() const, which:
Returns a null pointer if fail() returns true, otherwise returns a non-null pointer. This pointer is implicitly convertible to bool and may be used in boolean contexts.
Thus, in the expression:
cin==(cout<<(f(a)==f(b)?"YES":"NO"));
we would print either "YES" or "NO", and the result of the stream output would be cout still (in the form of a std::ostream&). When we do the equality check, both operands would be implicitly converted to void* and so the expression checks to see if both streams failed. This is a particularly obfusticated way of doing:
cout << (f(a) == f(b) ? "YES" : "NO");
return cin.fail() && cout.fail();
C++11
With C++11, the operator void*() const is replaced by explicit operator bool() const. The explicit is key, as it means that the conversion function can only be used explicitly (as in, via a direct cast) or in a boolean context, as in:
if (cin) { // calls cin.operator bool()
}
Equality is not a boolean context, so in the expression
cin == cout
that conversion function will not be invoked. As there is no operator== defined on std::basic_ios (or std::istream or std::ostream), the expression will simply not compile.
I am checking one code and getting confused by this line.
if( cout > 0 )
{
//some statements
}
Please tell me if we can use cout like that. And how it will work?
cout is a variable of the type ostream (or some type derived thereof). The ostream has a conversion to void *(pre-C++11) or bool (C++11) - both of these conversion functions check for "error status" in the filestream, and return NULL or false respectively if there is an error). Both these will compare to zero as zero is the same as NULL and false respectively and thus the statement becomes (void *)cout > NULL or (bool) cout > false, which will be true if cout is not NULL or false (this means "has no error").
[Note: a pointer comparison with NULL may not work correctly when using p > NULL, since pointers may be "negative", in which case it isn't greater than NULL - I would prefer to see if (cout != 0) or if (!cout) as a safer/better choice].
std::cout inherits an explicit operator bool() (C++11) or operator void*() (pre-C++11) from std::basic_ios. Both of these have the ability to be compared with 0. However, each has a problem:
The operator void*() conversion will (thanks to James Kanze for pointing this out below) not be guaranteed to work as expected. The 0 will be converted to a void * as well, and then, since one is null and one is not, the comparison is unspecified (N3485 § 5.9/2).
The explicit operator bool() conversion will not be triggered in this context, causing that to not compile. However, I don't think there is any main library implementation that uses this over the operator void*() yet, even though they should. Clang might have this done for next release if it's C++11-complete.
I'm curious how the fstream class is able to return a true or false value by simply placing the name of the object inside a conditional statement. For example...
std::fstream fileStream;
fileStream.open("somefile.ext");
if (!fileStream) // How does this work?
std::cout << "File could not be opened...\n";
I ask this because I want my own class to return a value if I use it in a similar way.
It's not really that it is equal to true or false, but rather that it overloads the ! operator to return its status.
See http://www.cplusplus.com/reference/iostream/ios/operatornot/ for the details.
Doing this yourself is very simple, check out the operator overloading faq or C++ Operator Overloading Guidelines.
Edit:
It's been pointed out to me that ios also overloads the void * conversion operator, returning a null pointer in the case of a failure. So you could also use that approach, also covered in the previously mentioned faq.
This works using a conversion operator. Note that the seemingly obvious way, conversion to bool, has unintended side effects, therefore a conversion to a built-in type with implicit conversion to bool should be used, e.g.:
class X
{
public:
void some_function(); // this is some member function you have anyway
operator void(X::*)() const
{
if (condition)
return &X::some_function; // "true"
else
return 0; // "false"
}
};
In C++11, you can make the conversion to bool explicit, and thus avoid the unintended side effects. Thus in C++11 you can simply write:
class X
{
public:
explicit operator bool() const
{
return condition;
}
};