Protected member function address in derived class is not accessible

后端 未结 3 1491
故里飘歌
故里飘歌 2021-01-11 21:38
#include 

class A {
protected:
    void foo()
    {}
};

class B : public A {
public:
    void bar()
    {
       std::cout << (&A::foo) &         


        
3条回答
  •  日久生厌
    2021-01-11 22:22

    Seems I found the answer. If we could get pointer of member function we can call it for other objects of type A (not this) which is not allowed.

    It is not allowed to call protected member function in derived classes for objects other than this. Getting pointer would violent that.

    We can do something like this:

    #include 
    
    class A {
    protected:
        void foo()
        {}
    };
    
    class B : public A {
    public:
        void bar()
        {
            void (A::*fptr)() = &A::foo;
    
            A obj;
            (obj.*fptr)();
    
            // obj.foo(); //this is not compiled too.    
        }
    };
    
    int main()
    {
        B b;
        b.bar();
    }
    

提交回复
热议问题