class foo {
public:
...
operatorvoid*() const { return m_p; }
operatorint() const { return m_i; }
...
};
...
foo f;
f = 42;
int n = f; // n is 42 because of operator int()
This is great. But, now:
1 2 3 4 5 6 7 8 9
class Bar {
public:
Bar(int);
};
foo f;
f = 42;
Bar *b = new Bar(f); // won't compile
Bar *bb = new Bar((int)f); // will compile, and use 42 as the arg.
So, my question is: why wouldn't the compiler implicitly convert f to an int - which would call my cast operator (as in the "bb" case)?
So, my question is: why wouldn't the compiler implicitly convert f to an int
You should find that f = 42;
does not compile, while Bar *b = new Bar(f);
Is acceptable.
int n = f; // n is 42 because of operator int()
Even if it did compile, this would not be the behavior (unless f.m_i was 42 beforehand) because the expression f.operator int() is a prvalue. Assigning to it would modify a materialized temporary object, not f.
Please provide a complete example of the code that doesn't compile.
Okay. Sorry guys. I don't know why this didn't compile before. Actually, it was in another IDE, probably with different compiler settings. But, this is what I wanted, and this does compile and work: