About a pointer to a member function of a derived class

Here my code and IDE is DEV C ++ 11

#include<iostream>
using namespace std;

class A{
    public:
        int a=15;
};
class B:public A
{

};
int main(){

    int A::*ptr=&B::a; //OK
    int B::*ptr1=&A::a; //why?
    int B::A::*ptr2=&B::a;//why?
    int B::A::*ptr3=&A::a;  //why?

} 

I read programming languages - C ++, and I know what kind of &B::athere int A::*, but I do not understand why these three lines will pass compilation. And the strangest thing for me is the syntax int B::A::*, what is the meaning of this? I'm just new to C/C++, so please bear with my weird question.

+6
source share
1 answer

Displaying charts can help you understand why this is normal and compiles int A :: * ptr = & B :: a;

int B :: * ptr1 = & A :: a;

int B :: A :: * ptr2 = & B :: a;

int B :: A :: * ptr3 = & A :: a

Interestingly, after reinitializing the same variable in an inherited class

#include<iostream>
using namespace std;

class A {
public:
    int a = 15;
};
class B :public A
{
public:
    int a = 10;
};
int main() {

    int A::*ptr = &B::a; //Waring class B a value of type int B::* cannot be 
                         //used to initialize an entity of type 'int A::*'
    int B::*ptr1 = &A::a; // why?
    int B::A::*ptr2 = &B::a;//Waring class B a value of type int B::* cannot                            
                      // be used to initialize an entity of type 'int A::*'
    int B::A::*ptr3 = &A::a;  //why?

}
+1
source

All Articles