3

I know from c++ primer that we can use typedef in the following ways:

typedef int mytype;
typedef int *mytype;

However, the following code also compiles, and it seems to create a new type "rt", I am curious what is the type of rt, and what are common uses of this kind of typedef?

class A{
public:
    int c;
};
typedef int A::* rt;
Casualet
  • 295
  • 3
  • 12

2 Answers2

5

It is not a "three elements typedef", it is a pointer to member variable typedef. You can find more information about pointer to member variable here.

In your precise case, it allows you to instantiate variables of type "rt" that will point to a precise member of type int of A class, and then use it to access this member on A instances.

#include <iostream>

class A{
public:
    int c;
};
typedef int A::* rt;

int main() {
  A instance;
  rt member; // This is a pointer to A member.
  member = &A::c; // This pointer will point on c member of A class

  instance.c = 0;
  instance.*member += 2; // As member point on c, this code access to the c member.
  std::cout << instance.c << std::endl; // This will now output "2".
}
Community
  • 1
  • 1
Aracthor
  • 5,757
  • 6
  • 31
  • 59
2

It's pointer to member variable. You define it with this syntax: int A::* pointer;, and initialize it $A::c and read it's value instance.*pointer.

A instance; int A::* pointer = &A::c; instance.*pointer = 10;

Actually it's an offset from beginning of the class that allow you to hold a pointer to int that is a member variable of class A.

MRB
  • 3,752
  • 4
  • 30
  • 44