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
?
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
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With