Problem with pointer-to-class-data-member

W

WaterWalk

(Sorry if I duplicated this post. My previous post somehow
disappeared.)

Hello. I am rather confused about pointers to class data members. Take
the following class as an example:
class MyClass
{
public:
int n;
};

I can use the pointer-to-member syntax to access MyClass::n:
typedef int MyClass*pn_t;
pn_t pn = &MyClass::n;
MyClass my;
my.*pn = 123;

But at the same time, the common pointer-to-data also seems to work:
MyClass my;
int *pn = &my.n;
*pn = 123;

I don't know if the second method is legal in c++ standard. If it is,
why bother to have the first method?
 
O

Old Wolf

I can use the pointer-to-member syntax to access MyClass::n:
typedef int MyClass*pn_t;

This is a syntax error. I think you meant:
typedef int MyClass::* pn_t;

although I never use that syntax so I could be wrong.
Also, pointer typedefs are confusing, so I suggest not
using them until you grok the subject matter.
pn_t pn = &MyClass::n;
MyClass my;
my.*pn = 123;

But at the same time, the common pointer-to-data also seems to work:
MyClass my;
int *pn = &my.n;
*pn = 123;

I don't know if the second method is legal in c++ standard.
Yes

If it is, why bother to have the first method?

Well, they do different things. The first pointer is
not bound to any particular class instance. In the
first one you could write:
MyClass mz;
mz.*pn = 456;

and there is no such equivalent for the second version.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,792
Messages
2,569,639
Members
45,353
Latest member
RogerDoger

Latest Threads

Top