Problem with pointer-to-class-data-member

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • WaterWalk

    #1

    Problem with pointer-to-class-data-member

    (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

    #2
    Re: Problem with pointer-to-class-data-member

    WaterWalk wrote:
    (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


    Comment

    • Old Wolf

      #3
      Re: Problem with pointer-to-class-data-member

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

      Comment

      Working...