Sign in to follow this  
nlbs

both operator&() and operator*() is overloaded

Recommended Posts

If a Class overloads both operator&() and that method returns something other that returning the address of actual object (itself). also if it overloads operator*() and that also returns something else other that returning the actual Object (itself) Whats the way to get the real address of the object. If I ask myself I get the answer there is no way. Is my answer right ??

Share this post


Link to post
Share on other sites
You can cast an object reference to a reference to a type that has a valid unary & behavior, and take the address of that. Ex:

struct A {
A * operator &() { return 0; }
};

int main(int, char **) {
A a;
int & i = reinterpret_cast<int &>(a);
std::cout << &a << "\n";
std::cout << &i;
}

Technically, this is implementation specific behavior that may or may not actually result in the address of a. Your mileage may vary.

Share this post


Link to post
Share on other sites
Quote:
If a Class overloads both operator&() and that method returns something other that returning the address of actual object (itself).
also if it overloads operator*() and that also returns something else other that returning the actual Object (itself)

If you overload the bitwise AND operator then there is no problem as it requires a rhs argument to make sense, similarly if you overload the arithmetic multiplication operator.

struct foo
{
foo operator& (foo& f){return *this;}
foo* operator& (){return this;}
};
#include <iostream>
int main()
{

foo f;
foo* fp(&f);
std::cout <<fp <<std::endl;
}



If you are not doing the above then maybe you should reconsider what your operators are doing and if overloading them is __correct__.

Share this post


Link to post
Share on other sites
Classes such as CComPtr that overload operator & can be a problem when trying to store them in certain containers. The solution used there is to wrap them in CAdapt objects. CAdapt is pretty simple. It's just a class that holds the type you give it (so it's the same size as that) and it doesn't overload the & operator.
You may wish to study that class.

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