1

I am trying to implement Observers and a Subject design pattern...

I have a object Subject, with a vector of pointers to Observers. Each Observer has a pointer to a function. How do I call it?

In this class, it's defined the function that I want to call

class functions_class
{
  static bool getVal(){
     return true;
  }
};

In this class, the vector containing the observer is defined

class Subject
{
      vector<Observer*> mViews;

   public:
      void addObserver(Observer *o)
      {
         mViews.push_back(o)
      }
};

In this class, the function pointer is stored. There is a function to call this pointer

class Observer
{
   typedef bool(*boolPtr)(void);
   boolPtr mPtr;

   Observer(boolPtr ptr)
   {
      mPtr = ptr;
   }

   bool call()
   {
      return (mPtr)();
   }
};

This is where objects are created

    Subject s;
    Observer o(functions_class::getVal);
    s.addObserver(&o);

QUESTION......... How do I call the function pointer in observer?? I'm using a generic function in observer, but I can't make it work.

I tried:

(s.mViews[0].call)()

Any idea?

Is it also possible to cast the output of the function call to an uint32_t?

1
  • Try s.mViews[0]->call(); Commented Jul 13, 2016 at 2:04

1 Answer 1

5

What is s.m_views[0]? Well, according to the shown code, the m_views class member is a

vector<Observer*> mViews;

Therefore, s.m_views[0] gets you an Observer *.

So, it logically follows, that given that this is a pointer, then:

s.m_views[0]->call()

This invokes the member function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.