• Advertisement
Sign in to follow this  

Can't access private members VC++

This topic is 4205 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm trying to implement the observer design pattern as follows:
//Observer.h
#include <Subject.h>
class Observer
{
  public:
    Observer() {}
    virtual ~Observer() {}
  private:
    virtual void notify() {}
    friend class Subject;
}

//Subject.h
#include <Observer.h>
#include <stdlib.h>
class Subject
{
  public:
    Subject();
    virtual ~Subject();

    void registerObserver(Observer& o);
    void unregisterObserver(Observer& o);
  private:
    virtual void notifyAll();
    std::vector<Observer*> m_list;
}

//Class A.h
class A : public Subject
{
  ...
}

//A.cpp
...
void A::notifyAll()
{
  if(m_list.size() <= 0)
    return;

  for(std::vector<Observer*>::iterator I = m_list.begin(); I != m_list.end(); I++)
  {
    ((Observer*) I)->notify();  // C2248
  }
}

I keep getting compiler error C2248: 'notify': cannot access private member declared in class 'Observer' afaik, the friend class i did in observer.h should allow subject to use it's private method. I'm using Visual C++ 6.0 service pack 6. Can anyone shed some light on this?

Share this post


Link to post
Share on other sites
Advertisement
Friendship is not inherited. Use a "notify" protected function on your Subject that notifies the Observer, and call this function from methods of A. Such as:

Subject::Notify(Observer& ob) { ob.notify(); }

In unrelated news, doesn't VC6 provide cstdlib (as opposed to non-standard stdlib.h) ?

Share this post


Link to post
Share on other sites
My C++ is poor, but my first thought was, is the friend modifier inheritable?

P.S. Upgrade now.

EDIT: Damn, beaten.

Share this post


Link to post
Share on other sites
Even when VC++ does it right, people assume it is wrong.

Isn't that nice?

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement