It's been a while since I did much with c++. I am trying to implement an the observable pattern, by passing in derived classes of an Observer class and storing them in a vector<Observer>
. I know I am passing in a derived class object, because the call to the notify()
method in the registerObserver()
method call the derived class method. When I get the objects out of the vector and call the notify method I get the base class method.
I am pretty sure it's either (or both) the call to push_back(observer)
that is creating a copy of the derived class as a base class object, or the for(Observer o : observers) {
that is the cause of the problem.
Here is the code of interest:
the base class
// Observer.h
class Observer
{
public:
virtual void notify();
};
// Observer.cpp
void Observer::notify()
{
Serial.println("got a notification in base class");
}
the derived class
// DatabaseUpdater.h (derived class)
class DatabaseUpdater : public Observer
{
public:
void notify() override;
};
// DatabaseUpdater.cpp
void DatabaseUpdater::notify()
{
Serial.println("got a notification in database class");
}
the subject class
// HwMonitor.h (subject class)
class HwMonitor
{
public:
void registerObserver(Observer& observer);
void event();
private:
std::vector<Observer> observers;
};
//HwMonitor.cpp
void HwMonitor::registerObserver(Observer &observer)
{
Serial.println("adding observer");
observer.notify();
observers.push_back(observer);
}
void HwMonitor::event()
{
Serial.println("event");
for(Observer o : observers) {
o.notify();
}
}
the "main" (Ardunio)
//app.ino
DatabaseUpdater o;
HwMonitor esp;
void setup()
{
Serial.begin(115200);
delay(2000);
Serial.println("registering observer");
esp.registerObserver(o);
}
void loop()
{
Serial.println("calling an event");
esp.event();
delay(1000);
}