Sign in to follow this  
YellowMaple

Can't access private members VC++

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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this