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.
Diagram representation may help you understand why it is ok and compiles
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?
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With