1

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 ?

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
Davidbrcz
  • 2,335
  • 18
  • 27
  • This answer https://stackoverflow.com/questions/49550663/access-to-protected-member-through-member-pointer-is-it-a-hack is for fields but the reasoning should be same, – Davidbrcz Sep 03 '21 at 10:40

1 Answers1

3

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

Caleth
  • 52,200
  • 2
  • 44
  • 75