Operator Overloading
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?
-EDIT: Erased incorrect answer, to prevent misinformation
[Edited by - mikeman on July 4, 2008 3:51:21 AM]
[Edited by - mikeman on July 4, 2008 3:51:21 AM]
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".
"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".
It is an implicit casting mechanism. If you have:
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().
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().
Crap. I should get some sleep, I completely misunderstood, well...pretty much anything. My apologies to the OP :)
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement