Error: 'void Base :: output ()' is protected in this context

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

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

(I thought that protected / closed is controlled, is it possible to use the name in a certain context, but apparently this is incomplete?)

Is my writing fix callback(this, &Derived::output);instead of the callback(this, Base::output)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();
}

: , , . , , callback Derived, Derived::output, . Derived, Derived, Derived, Base?

+3
2

, " ". ? , , .

, 11.5.1 ( ++ 0x FCD):

11 , - (11.2) 114 , , - C. (5.3.1), - C , C. (, ) (5.2.5). case, C C.

Edit:

, , , , , ( ) :

void (Base::*derivedPointer)() = &Derived::output;
+2

: , " ?" " ?" , ( )

, , base , , base .

callback base .

+1

Source: https://habr.com/ru/post/1740192/


All Articles