Hello I am new to C++ and I am trying to understand the subject observer pattern. Here is what I have been working on based on an example form the design patters book.
#include <vector>
#include <iostream>
class Subject;
class Observer
{
public:
virtual void notify(Subject* s) = 0;
};
class Subject
{
std::vector<Observer*> *observers;
protected:
void notify_observers()
{
std::vector<Observer*>::iterator iter;
for (iter = observers->begin(); iter != observers->end(); ++iter)
(*iter)->notify(this);
}
public:
void register_observer(Observer* o)
{
observers->push_back(o);
}
};
class Horn : public Observer
{
public:
virtual void notify(Subject* s)
{
std::cout << "Horn with id " << s->get_alarm_id << " is sounding\n";
}
};
class Alarm : public Subject
{
public:
Alarm()
{
std::cout << "alarm created" << "\n";
}
void triggerd()
{
std::cout << "The alarm has been triggerd" << "\n";
notify_observers();
}
int const get_alarm_id(){ return 100; }
};
int main ()
{
Alarm a = Alarm();
Horn h = Horn();
a.register_observer(&h);
a.triggerd();
return 0;
}
Basically I want to push the subject class to the observer so the observer can get information form the subject. However When the notify method is called it gets the subject object not the alarm object. Can someone tell me how to ensure that the alarm object is getting passed.