Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: All
Dec 17, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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
Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date