Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Beginner
Sep 4, 2001

Detecting the vptr's Location

The precise location of the vptr (the pointer to the class's table of virtual functions' addresses) is implementation-dependent. Some compilers, e.g., Visual C++ and C++ Builder, place it offset 0, before the user-declared data members. Other compilers, such as GCC and DEC CXX, place the vptr at the end of the class, after all the user-declared data members. Normally, you wouldn't care about the vptr's position. However, under certain conditions, for example, in applications that dump an object's content to a file so that it can be retrieved afterwards, the vptr's position matters. To detect it, first take the address of an object that. Then compare it to the address of the first data member of that object. If the two addresses are identical, it's likely that the vptr is located at the end. If, however, the member's address is higher than the object's address, this means that the vptr is located at the object's beginning. To detect where your compiler places the vptr, run the following program:
class A
 virtual void f() {}
 int n;

int main()
 A a;
 char *p1=reinterpret_cast <char *> (&a);
 char *p2=reinterpret_cast <char *> (&a.n);
 if (p1==p2)
  cout<<"vptr is located at the object's 
  cout<<"vptr is located at the object's 
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