Reputation: 1864
I googled, but didn't find a clear answer. Example:
class Foo {
public:
operator void* () {
return ptr;
}
private:
void *ptr;
};
I understand what void* operator()
is. Is the above operator the same thing in a different syntax? If not, what is it? And how can I use that operator to get the ptr
?
Upvotes: 11
Views: 8222
Reputation: 32502
That function defines what happens when the object is converted to a void pointer, here it evaluates to the address the member ptr
points to.
It is sometimes useful to define this conversion function, e.g. for boolean evaluation of the object.
Here's an example:
#include <iostream>
struct Foo {
Foo() : ptr(0) {
std::cout << "I'm this: " << this << "\n";
}
operator void* () {
std::cout << "Here, I look like this: " << ptr << "\n";
return ptr;
}
private:
void *ptr;
};
int main() {
Foo foo;
// convert to void*
(void*)foo;
// as in:
if (foo) { // boolean evaluation using the void* conversion
std::cout << "test succeeded\n";
}
else {
std::cout << "test failed\n";
}
}
The output is:
$ g++ test.cc && ./a.out
I'm this: 0x7fff6072a540
Here, I look like this: 0
Here, I look like this: 0
test failed
See also:
Upvotes: 6
Reputation: 409166
No they are two different operators. The operator void*
function is a type casting function, while operator()
is a function call operator.
The first is used when you want to convert an instance of Foo
to a void*
, like e.g.
Foo foo;
void* ptr = foo; // The compiler will call `operator void*` here
The second is used as a function:
Foo foo;
void* ptr = foo(); // The compiler calls `operator()` here
Upvotes: 15
Reputation: 33579
It's a type conversion operator. It is used whenever an object of class Foo
is casted (converted) to void*
. It is indeed not the same as void* operator()
.
Upvotes: 1