Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it impossible to get a pointer to a protected method of the base class? [duplicate]

class A {
public:
   A() {auto tmp = &A::foo;}
protected:
   void foo() {}
};

class B : public A {
public:
   B() {auto tmp = &A::foo;}
};

Class A compiles no problem. Class B yields a compilation error:

'A::foo' : cannot access protected member declared in class 'A'

Why is that, what's the rationale? Is there a way to circumvent this (if I need that pointer for a callback, std::function etc.)?

like image 214
Violet Giraffe Avatar asked Jul 25 '14 10:07

Violet Giraffe


People also ask

Who can access protected methods C++?

Only the member functions or the friend functions are allowed to access the private data members of a class.

Can you override a protected method C++?

Yes, the protected method of a superclass can be overridden by a subclass. If the superclass method is protected, the subclass overridden method can have protected or public (but not default or private) which means the subclass overridden method can not have a weaker access specifier.

How do you access protected methods outside a class?

The protected access modifier is accessible within the package. However, it can also accessible outside the package but through inheritance only. We can't assign protected to outer class and interface. If you make any constructor protected, you cannot create the instance of that class from outside the package.


1 Answers

Why is that, what's the rationale?

In general, a derived class can only access protected members of the same derived class, not of the base class itself or arbitrary classes with the same base class. So B can access protected members of A via B, but not directly via A.

Is there a way to circumvent this?

The inherited member is also a member of B, and can be accessed as such:

auto tmp = &B::foo;
like image 161
Mike Seymour Avatar answered Oct 04 '22 00:10

Mike Seymour