I'm wondering if and how to make a class return an integer without calling a member function.

Example

Code:

int bar (int a);

int main()
{
Foo f(); // create a Foo object

// Example A
int a;

a = f + 1; // Treat f as an int

// Example B
a = bar(f); // Treat f as an int

// Example C
return f; // Treat f as an int
}

Example A can be done with operator overloading. But what about B and C?

I want to do this so I can make a class, FifoPtr, that behaves exactly like an int except when assigning a new value to it, it does a (% size) before assigning. I'd like to do it without having to call Foo::get_val() or something in examples B and C.

>>Foo f(); // create a Foo object
This is wrong. This declares a function returning a Foo object.

As for the question... yes, it's possible.
Simply overload an operator int() in the class. You should consider making it explicit if your compiler supports it.
If it doesn't support explicit conversion operators (C++11 feature), then I recommend that you use a get function to avoid evil implicit conversions.

09-10-2011

_Mike

Quote:

Originally Posted by Elysia

[...]explicit conversion operators (C++11 feature), [...]

Wow, that's awesome. I have been wishing for that type of feature. :)

09-10-2011

BdON003

Perfect. I haven't used C++ in awhile. I forgot about conversion operators.