C++ Address-of Idiom | Get address of object of overloaded ‘&’ operator
To get the Address of object of overloaded address-of ‘&’ operator.
The idiom presented in this article is no longer needed to be written manually on the compiler that supports at least c++11 standard. Same function can be achieved by “std::addressof()” function in “<memory>” header should be used instead. This article just give the idea and the reason to use such function.
While the feature of OOP language like C++ to overload operators gives greater flexibility to programmer but this freedom can be pain if not used properly.
In C++ ’&’ operator is known to extract the address of object but as C++ allow the overloading of ‘&’ operator and programmer can misuse it to not return the actual address of the object. This behavior is enough to break the general structure of program.
For Example, take a look at below program
In the above code, As print() function accept pointer to the object of both class and print it’s member a, so we are passing object of both class from main() function. Things go wrong as ‘&w’ will return the address of ‘int’ type as programmed in ‘Wrong’ class. Below is the actual error reported by gcc-10 indcating type mismatch.
Solution and Sample Code
This is where we need address-of-idiom.
Note:- As mentioned before this idiom is already present in STL on c++11 and afterward, so use that instead.
The central idea of this idiom is to pass the object through series of ’Primitive type’ type casting.
We created additional function called addressof(T& obj) taking the reference of object, make it pass through the series of cast and thus returning the actual address of object provided in argument.