[Solved] Problem Implementing Observer Pattern : “Member reference base type ________ is not a structure or union”

I’ve been implementing a barebones observer pattern and am stuck on a somewhat cryptic error:
“Member reference base type ‘Observer *’ is not a structure or union”. I assume this has something to do with my use of templates, with which I’m still fairly uncomfortable. Here is the offending code (most cons/destructors removed to simplify things):

Subject interface:

class Subject { 
public:
    virtual void notify();
private:
    list< Observer * > m_observers; 
};

Subject implementation:

void Subject::notify() {
    list< Observer * >::iterator i;

    for ( i = m_observers.begin(); i != m_observers.end(); i++ ) {
        *i->update( this );                        // ERROR !!! ERROR
}

Observer abstract interface:

class Observer {
public:
    virtual ~Observer();
    virtual void update( Subject * changedSubject ) = 0;

protected:
    Observer();
};

Concrete Observer interface:

class ConcreteObserver: public Observer {

public:
    ConcreteObserver( ConcreteSubject * );
    virtual ~ConcreteObserver();

    virtual void update( Subject * changedSubject );

private:
    ConcreteSubject * m_subject;
};

Concrete Observer implementation:

void ConcreteObserver::update( Subject * changedSubject ) {
    if ( changedSubject == m_subject ) {
        report();
    }
}

If anyone could help identify this problem, I would greatly appreciate it.

Cheers,
Nick

Solution #1:

The problem is with the operator precedence. Instead of:

*i->update( this );

Use:

(*i)->update( this );

Otherwise, it will be interpreted as *(i->update( this )), which tries to call a method on a pointer, resulting in the error message.

Respondent: interjay

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.