ram
ram

Reputation: 73

What does the following code mean in c++?

struct Dog{  
  int a;  
  int b;  
};

int Dog::*location = &Dog::a  
Dog* obj1 = new Dog;  
obj1->*location = 3;  

what does &Dog::a refer to?

Upvotes: 4

Views: 209

Answers (3)

Greg Hewgill
Greg Hewgill

Reputation: 993015

The variable location is known as "member data pointer". It's a pointer to something inside a structure, but doesn't make sense unless it's used with an actual object pointer. The use of *location by itself would not be enough information to resolve to an actual address, but obj1->*location refers to an actual location.

Upvotes: 2

Ben Voigt
Ben Voigt

Reputation: 283634

It creates a pointer-to-member, which is like a pointer to a data member of a class, but the class instance isn't determined yet, it's just the offset. (Note, when combined with multiple inheritance or virtual inheritance, it gets quite a bit more complicated than a simple offset. But the compiler works out the details.)

Notice the pointer-to-member dereference operator ->* used in the last line, where the class instance is combined with the pointer-to-member to yield a particular data member of a particular instance.

Upvotes: 4

Marino Šimić
Marino Šimić

Reputation: 7342

& means take the adress of something.

Upvotes: -2

Related Questions