C++ Idiom : Address-of | Get address of object of overloaded ‘&’ operator

Intent

To get the address of object of a class that have overloaded ‘&’ operator that do not return real address of object

Side Note

The idiom presented in this article is no longer needed to be hand written on the compiler that supports at least c++11 standard. More tested std::addressof() in header <memory> should be used instead. This article just give the idea and the reason to use such function.

Motivation

C++ allows address-of operator(&) to be overloaded inside the user defined type. That overloaded operator need not strictly return the actual address of the object. Some class misuse this power and create a confusion especially when used in library code. However such action should be done very carefully as it break the general structure of code. For the quick example look at the code below in picture. In the following code we had created a class Demo and overloaded ‘&’ operator to return address of data member i.e {int a}. The operation inside main() for both class (‘Fine’ and ‘Demo’) is same but assignment of address of d2 to d1 gives the very very unexpected error. If the similar code is inside the library where we cannot modify source it is very unpredictable to know the actual intent of doing so.

img

However if we are supposed to solve the error then what we need is to write address-of idiom.

Solution and sample code

The main idea of this idiom is to get the actual address of provided object by making the given argument go through series of cast

img

You can get the source code of the example used in this article at https://github.com/sudipghimire533/learning/blob/master/idioms/addressof.cpp

Reference

https://en.cppreference.com/w/cpp/memory/addressof


You have the power

You can Edit this article or even Submit new articles. Want to Learn more?