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

Intent

To get the Address of object of overloaded address-of &’ operator.

Side Note

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.

Motivation

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

Overloaded & operator with not-general purpose

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.

Error generated by gcc-10 to above program

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.

Reference

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

--

--

--

Developer on rise.

Love podcasts or audiobooks? Learn on the go with our new app.

Maybe native executable in Quarkus is not for you, but it is awesome

Fear of the code review

The Best Way to Manage your .env Files ft. Dotenv Vault

12 Misconceptions about Virtual Warehouses in Snowflake

ZKSwap Will Allocate Portion of 1993 NFTs to Existing Token Holders — March 12 Operational…

Let’s Get on Cloud

Switchboard raises 3.5MM seed and announces Solana Mainnet Beta

How To Improve Programming Logic

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sudip Ghimire

Sudip Ghimire

Developer on rise.

More from Medium

Huffman Algorithm

CS371p Spring 2022: Santi Dasari: Final Entry

Consuming ML Requests by Using SQS and Multiprocessing