Connecting Tech Pros Worldwide Forums | Help | Site Map

Problem with pointer-to-class-data-member

WaterWalk
Guest
 
Posts: n/a
#1: Sep 18 '07
(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?


Victor Bazarov
Guest
 
Posts: n/a
#2: Sep 18 '07

re: Problem with pointer-to-class-data-member


WaterWalk wrote:
Quote:
(Sorry if I duplicated this post. My previous post somehow
disappeared.)
[..]
No, it didn't. I just replied to it.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask


Old Wolf
Guest
 
Posts: n/a
#3: Sep 18 '07

re: Problem with pointer-to-class-data-member


On Sep 18, 2:52 pm, WaterWalk <toolmas...@163.comwrote:
Quote:
>
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.
Quote:
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
Quote:
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.

Closed Thread