error: 'void Base::output()' is protected within this context

Posted by Bill on Stack Overflow See other posts from Stack Overflow or by Bill
Published on 2010-04-07T16:28:35Z Indexed on 2010/04/07 16:33 UTC
Read the original article Hit count: 145

Filed under:
|

I'm confused about the errors generated by the following code. In Derived::doStuff, I can access Base::output directly by calling it.

Why can't I create a pointer to output() in the same context that I can call output()?

(I thought protected / private governed whether you could use a name in a specific context, but apparently that is incomplete?)

Is my fix of writing callback(this, &Derived::output); instead of callback(this, Base::output) the correct solution?

#include <iostream>
using std::cout; using std::endl;

template <typename T, typename U>
void callback(T obj, U func)
{
  ((obj)->*(func))();
}

class Base
{
protected:
  void output() { cout << "Base::output" << endl; }
};

class Derived : public Base
{
public:
  void doStuff()
  {
// call it directly:
    output();
    Base::output();

// create a pointer to it:
//    void (Base::*basePointer)() = &Base::output;
// error: 'void Base::output()' is protected within this context
    void (Derived::*derivedPointer)() = &Derived::output;

// call a function passing the pointer:
//    callback(this, &Base::output);
// error: 'void Base::output()' is protected within this context
    callback(this, &Derived::output);
  }
};

int main()
{
  Derived d;
  d.doStuff();
}

© Stack Overflow or respective owner

Related posts about c++

Related posts about access-modifiers