Home > Net >  Bypassing protected with inheritance and function pointer
Bypassing protected with inheritance and function pointer

Time:09-17

I've seen the following pattern used a couple of times to access protected member functions.

class A{
public:
    virtual ~A(){};
protected:
        void foo(){}
};

class B : public A{};


class Hacky : public B{
public:
    using B::foo;
};

int main(){
    B b;
    A& a = b;
    auto ptr = &Hacky::foo;
    (a.*ptr)();
}

I argue that this is undefined behavior following this page, Built-in pointer-to-member access operators, point 5 (here E1 dynamic type is B and it doesn't contain Hacky::foo), but I'm not 100% sure. Could some give a definitive answer on that ?

CodePudding user response:

The type of ptr is void (A::*)(), not void (Hacky::*)(), so it is fine.

  • Related