Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does operator void* () mean?

Tags:

c++

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?

like image 344
GuLearn Avatar asked Aug 13 '13 17:08

GuLearn


2 Answers

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
like image 154
Some programmer dude Avatar answered Oct 21 '22 05:10

Some programmer dude


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:

  • http://en.cppreference.com/w/cpp/io/basic_ios/operator_bool
like image 34
moooeeeep Avatar answered Oct 21 '22 05:10

moooeeeep