devxlogo

The Representation Of Pointers To Members

The Representation Of Pointers To Members

Although pointers to members behave very much like ordinary pointers, behind the scenes, they are not necessarily represented as pointers. In fact, a single pointer to member usually consists of a struct that contains between up to four fields, each occupying 4 bytes. This is because pointers to members have to support not only ordinary member functions, but also virtual member functions, member functions of objects that have multiple base classes, and member functions of virtual base classes. Thus, the simplest member function can be represented as a set of two pointers: one holding the physical memory address of the member function, and a second pointer that holds the this pointer. However, in cases like a virtual member function, multiple inheritance and virtual inheritance, the pointer to member must store additional information. Therefore, you cannot cast pointers to members to ordinary pointers nor can you safely cast one pointer to member to another; in both cases, the results are undefined.

To get a notion on your compiler’s represents pointers to members, you can measure their size. In the following example, the sizes of a pointer to data member and a pointer to a member function are taken. As you can see, they have different sizes, hence, different representations:

   struct A  {    int x;    void f();  };  int A::*pmi = &A::x;  void (A::*pmf)() = &A::f;  int n = sizeof (pmi);  // 8 byte on my compiler  int m = sizeof (pmf); // 12 bytes on my compiler
See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist