Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About pointer to member function of derived class

Here's my code, and the 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 have read Programming Languages — C++ and I know the type of &B::a is int A::*, but I don't realise why the next three lines will pass the compilation. And the weirdest thing to me is the syntax of int B::A::* , what's the meaning of this? I'm just a newcomer of C/C++, so please tolerate my weird question.

like image 621
BooAA Avatar asked Jul 21 '17 14:07

BooAA


1 Answers

Diagram representation may help you understand why it is ok and compiles int A::*ptr = &B::a;

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

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

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

Interesting will be once you reinitialize the same variable in 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?

}
like image 104
Hariom Singh Avatar answered Oct 16 '22 09:10

Hariom Singh