This topic is 3489 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Normally I use: Interface& operator*() {......} and Interface* operator&() {......} However as I was looking through the _com_ptr_t template class that was provided by vc++ I came across this: operator Interface*() const {......} and operator Interface&() const {......} what does these type of operator overload means? How is it used?

##### Share on other sites
-EDIT: Erased incorrect answer, to prevent misinformation

[Edited by - mikeman on July 4, 2008 3:51:21 AM]

##### Share on other sites
No, these are typecast operators. Since the return value of a typecast must be the type you are casting to, there is no need to specify the return type separately.

"Interface& operator*()" is called for "*anObject", while
"operator Interface&()" is called for "(Interface&)anObject".

You can also do this with primitives: "operator int()", will be called for "(int)anObject".

##### Share on other sites
It is an implicit casting mechanism. If you have:
class Foo {   int f;};class Bar {public:    operator Foo &() { return foo; }    operator const Foo&() const { return foo; }private:    Foo foo;};void example( const Foo & ){}int main(){     Bar bar;     Foo foo = bar; // allowed     example(bar); // allowed}

It is considered dangerous because it may no longer be clear why the code compiles. In the above example if Foo and Bar were in separate header files, without looking I would have expected the code in main marked "allowed" to fail. Using an operator like asterisk or -> is a little more explicit because it is obvious you are doing something with the variable. This approach works well when the result of the dereference would be obvious, like some_smart_ptr<T>::operator*() would be expected to return a T &. The best way is usually to have an explicit function call, like std::string::c_str().

##### Share on other sites
Crap. I should get some sleep, I completely misunderstood, well...pretty much anything. My apologies to the OP :)

##### Share on other sites
Thanks for the replies. No worries mikeman, when I came back to the forums you had already deleted the post :D