mardi 29 octobre 2019

Passing derived class to method as argument which is base class with smart pointer

I have read Head First Design Pattern recently. The book shows related codes in Java. However, I try to convert Java codes to C++. At Observer pattern chapter, I got stuck while converting somewhere. Related codes are follows.

class Subject{ //Publisher
public:
    virtual void registerObserver(ObserverPtr o) = 0;
    virtual void removeObserver(ObserverPtr o) = 0;
    virtual void notifyObservers() = 0;
};
using SubjectPtr = std::shared_ptr<Subject>;

Subscriber class interface:

class Observer{
public:
    virtual void update(double temp, double humidity, double pressure) = 0;
};

using ObserverPtr = std::shared_ptr<Observer>;

Display Element interface:

class DisplayElement{
public:
    virtual void display() = 0;
};

using DisplayElementPtr = std::shared_ptr<DisplayElement>;

and CurrentConditionsDisplay

class CurrentConditionsDisplay : public Observer, public DisplayElement{
    SubjectPtr m_weatherData;
    double temperature;
    double humidity;
public:
    CurrentConditionsDisplay(SubjectPtr weatherData);
    void update(double temperature, double humidity, double pressure);
    void display();

};

using CurrentConditionsDisplayPtr = std::shared_ptr<CurrentConditionsDisplay>;

My question:

At constructor of class CurrentCurrentConditionsDisplay, I would like that Publisher(Subject) registers CurrentCurrentConditionsDisplay.

//constructor
CurrentConditionsDisplay::CurrentConditionsDisplay(SubjectPtr weatherData) :
    temperature(0),
    humidity(0)
{
    m_weatherData = weatherData;

    /* How should I pass 'this' ? */
    m_weatherData->registerObserver(???????); //parameter type is ObserverPtr.

}

How should 'pointer this' is passed due to the fact that parameter type is ObserverPtr?

Aucun commentaire:

Enregistrer un commentaire