2

I was studying ns-3 tutorial. I cannot understand the following code snippet:

class MyObject : public Object
{
public:
  static TypeId GetTypeId (void)
  {
    static TypeId tid = TypeId ("MyObject")
       .SetParent (Object::GetTypeId ())
       .AddConstructor<MyObject> ()
       .AddTraceSource ("MyInteger",
                     "An integer value to trace.",
                      MakeTraceSourceAccessor (&MyObject::m_myInt))
       ;
     return tid;
  }

  MyObject () {}
  TracedValue<int32_t> m_myInt;
};

As I understand, MyObject::m_myInt is an access to non-static class member m_myInt from static method and & takes address of this member. This code is successfully compiled and executed. How can it be possible? What instance of class does the static method use?

Mahendra Gunawardena
  • 1,956
  • 5
  • 26
  • 45
user1558573
  • 385
  • 3
  • 7
  • This is actually a pointer to member (not a pointer to an instance's member). See [this question](http://stackoverflow.com/q/670734/1272627); It has some good answers. – Kaiged Jul 27 '12 at 21:00

1 Answers1

2

Pointers to members can be pointers to either member methods or member variables and do not need an instance of a class to be declared or assigned. This does not mean you can do much without an instance, however. You still need an instance to use them. Consider the following code:

class A
{
public:
    void SomeMethod();
    int someVar;
};

void (A::*pSomeMethod)() = &A::SomeMethod; //Declares a member pointer to method and assigns
int A::*pSomeVar = &A::someVar; //Declares a member pointer to int variable and assigns

A a; //Defines an instance
(a.*pSomeMethod)(); //Uses an instance with the pSomeMethod member pointer.
int var = (a.*pSomeVar); //Uses an instance with the pSomeVar member pointer.

It is possible, and it allows for some pretty cool stuff.

Kaiged
  • 609
  • 1
  • 7
  • 19