The following code gives an compilation error for void b() { m = &A::a; };
stating that A::a()
is protected. (Which it is - but that should be no problem)
However the compiler doesn't care when I write B::a()
. Even though both mean the same I would prefer A::a()
because it states explicitely that a()
is defined in A.
So what is the reason why A::a()
is forbidden?
EDIT
Maybe someone can find an example that would be problematic if A::a()
was allowed in B::b()
. If there is such an example, I will mark it as answer to the question.
/EDIT
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdio>
class A {
protected:
void a(){ std::cout << "A::a()" << std::endl; };
};
typedef void (A::*f)();
class B : public A {
public:
void b() { m = &A::a; }; // wont compile
// void b() { m = &B::a; }; // works fine
void c() { (this->*m)(); };
protected:
f m;
};
int main(){
B b;
b.b();
b.c();
}
// compile with
// g++ -Wall main.cpp -o main
Explanation of the code:
In B I want to store a function pointer to a method in A to be able to call that later in B::c()
. And yes, this happens in real life too. :-)