Why is “operator void” not invoked with cast syntax?

The technical reason why is found in ยง12.3.2: 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. The rationale is (likely) … Read more

operator= and functions that are not inherited in C++?

The assignment operator is technically inherited; however, it is always hidden by an explicitly or implicitly defined assignment operator for the derived class (see comments below). (13.5.3 Assignment) An assignment operator shall be implemented by a non-static member function with exactly one parameter. Because a copy assignment operator operator= is implicitly declared for a a … Read more

Possible to overload null-coalescing operator?

Good question! It’s not listed one way or another in the list of overloadable and non-overloadable operators and nothing’s mentioned on the operator’s page. So I tried the following: public class TestClass { public static TestClass operator ??(TestClass test1, TestClass test2) { return test1; } } and I get the error “Overloadable binary operator expected”. … Read more

Why can some operators only be overloaded as member functions, other as friend functions and the rest of them as 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 … Read more

‘friend’ functions and

Note: You might want to look at the operator overloading FAQ. Binary operators can either be members of their left-hand argument’s class or free functions. (Some operators, like assignment, must be members.) Since the stream operators’ left-hand argument is a stream, stream operators either have to be members of the stream class or free functions. … Read more

Invoke Operator & Operator Overloading in Kotlin

Yes, you can overload invoke. Here’s an example: class Greeter(val greeting: String) { operator fun invoke(target: String) = println(“$greeting $target!”) } val hello = Greeter(“Hello”) hello(“world”) // Prints “Hello world!” In addition to what @holi-java said, overriding invoke is useful for any class where there is a clear action, optionally taking parameters. It’s also great … Read more