Reputation: 25
I have already looked up some answers to this problem and got it working, but I can't seem understand how this one answer works, can someone enlighten me what is going on in the line void show(input& obj){cout <<obj.*&output::x <<' ' <<obj.*&output::y <<endl;}
.
Here is the full code:
#include <iostream>
using namespace std;
class baseClass{
protected:
int x, y;
public:
virtual void func()=0;
};
class input:public baseClass{
public:
void func(){
cout <<"Enter value x and y respectively: ";
cin >>x >>y;
cout <<endl;
}
};
class output:public baseClass{
public:
void func(){}
void show(input& obj){
cout <<obj.*&output::x <<' ' <<obj.*&output::y <<endl; /*Is this a reliable and effective
} way of calling the protected data members?*/
};
int main(){
baseClass* ptr;
input callIn;
output callOut;
ptr=&callIn;
ptr->func();
callOut.show(callIn);
}
I'm trying to access the protected data member of input class which is inherited from the parent baseClass by passing it object to another child class.
Upvotes: 0
Views: 35
Reputation: 62603
The code is legal, albeit convoluted and non-intuitive.
The gist of the magic happens here:
cout <<obj.*&output::x <<' ' <<obj.*&output::y <<endl;
Here, &output::x
denotes a pointer-to-member, namely x
in the output
class. This operation is permitted, since output
has baseClass
as it's parent and thus has access to it's protected members.
Now you can access a member in class input
using the pointer-to-member, as access controls do not control access through pointer-to-member (they can not!). They rely on control invoked during taking the address of the said member.
To make the code a bit more clear, one can use local variable to store pointer:
int baseClass::* p = &output::y;
cout << obj.*p << endl;
Also, while I find the technique worth understanding, I am not discussing whether it is appropriate to use. Often if you have to resort to magic tricks like this you might want to instead revisit your design and class hierarchy, but I would not rule out a potential use case for this.
Upvotes: 1