1

Suppose I have a class like this:

class Owner
{
private:
    long m_Id;
    QString m_Name;

public:
    Owner() : m_Id(0) { ; }
    virtual ~Owner() { ; }

    inline long id() const { return m_Id; }
    inline void setId(long id) { m_Id = id; }

    inline const QString & name() const { return m_Name; }
    inline void setName(const QString & name) { m_Name = name; }
}

I saw a code &Owner::m_Id;. I'm confused, does it return a pointer to the member? and if so, how can it be used on Owner's instances?

Shahbaz
  • 46,337
  • 19
  • 116
  • 182
Davita
  • 8,928
  • 14
  • 67
  • 119

1 Answers1

4

It does return a member pointer. You can use it to access m_Id indirectly, as follows:

long Owner::* ptrMem = &Owner::m_Id;
Owner owner;
owner.*ptrMem = 10;
cout << owner.m_Id << endl;

This code works in a context where m_Id is accessible, for example in a member function.

This example is not too interesting, because your class does not have other members of type long. In situations where multiple such members exist, member pointers become more valuable: you can postpone the binding to a particular member to run-time.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523