• Advertisement
Sign in to follow this  

Operator Overloading

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
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 this post


Link to post
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 this post


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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement