c++oopinheritancepointer-to-member

Get pointer to derived class member made public with using declaration


Consider a base class with a couple of public fields and a derived class which inherits the base privately and makes one of the inherited fields public via the using declaration. I need to access this public field of the derived class with a member pointer. Here is some code:

#include <iostream>

class Base
{
public:
    int derived_public_field = 1;
    int derived_private_field = 1;
};


class Derived : private Base
{
public:
    using Base::derived_public_field;
};


int main() {
    Derived d;
    int Derived::* member_ptr = &Derived::derived_public_field;
    d.*member_ptr = 2;
    std::cout << d.derived_public_field << '\n';
}

This does not work as the &Derived::derived_public_field expression results in the compiler (tried Clang and GCC) thinking that I'm trying to access an inaccessible base. GCC says:

error: 'Base' is an inaccessible base of 'Derived'

I also tried this:

int Base::* member_ptr = &Base::derived_public_field;

which just made the same error appear later, when I try to write a value via the pointer.

Is there a way to make the compiler see that derived_public_field is actually accessible?


Solution

  • #include <iostream>
    
    class Base {
    public:
        int derived_public_field = 1;
    private:
        int derived_private_field = 1;
    };
    
    class Derived : private Base {
    public:
        using Base::derived_public_field;
    };
    
    int main() {
        Derived d;
        auto bp = &Base::derived_public_field;
        auto dp = reinterpret_cast<int Derived::*>(bp);
        d.*dp = 2;
        std::cout << d.derived_public_field << '\n';
    }