Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

explicit object accessing a protected member

Tags:

c++

c++23

I'm trying to understand why this code will not compile:

class A {
   public:
    template <class Self>
    void invokeUser(this Self&& self) {
        self.invokeProtected();
    }
};

template <typename... Bases>
class B : public Bases... {
   protected:
    void invokeProtected() {}
};

int main() { B<A>{}.invokeUser(); }

It fails with the following error:

error: 'invokeProtected' is a protected member of 'B<A>'
note: in instantiation of function template specialization 'A::invokeUser<B<A>>'

It clearly sees it's being called with a B<A> reference, which is our "this" or "self" in this case. From that context we should be able to get access to the protected members, right? Is this something that the standard prohibits, or is this a clang bug?

like image 328
Martijn Otto Avatar asked Dec 03 '25 21:12

Martijn Otto


1 Answers

Member access checks are restrictions on uses of names to certain scopes.

A is not B, nor is it a subclass of B, nor a friend of B, so all the protected members of B are inaccessible within A. It doesn't matter that self is an explicit object argument.

like image 61
Caleth Avatar answered Dec 05 '25 12:12

Caleth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!