Sign in to follow this  
littlekid

Operator Overloading

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this