What does the void * () operator mean?

I googled but did not find a clear answer. Example:

class Foo { public: operator void* () { return ptr; } private: void *ptr; }; 

I understand what void* operator() . Is the above statement the same in another syntax? If not, what is it? And how can I use this operator to get ptr ?

+7
c ++
source share
3 answers

No, these are two different operators. The operator void* function is a type selection function, and operator() is the function call operator.

The first is used when you want to convert an instance of Foo to void* , for example, for example.

 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 
+15
source share

This function determines what happens when an object is converted to a void pointer, here it computes the address pointed to by the ptr member.

It is sometimes useful to define this conversion function, for example. for boolean evaluation of an object.

Here is 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"; } } 

Output:

 $ 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:

+5
source share

This is a type conversion operator. It is used whenever an object of class Foo cast (converted) to void* . This is really not the same as void* operator() .

0
source share

All Articles