Reputation: 1554
Following is some example code for using "member variable pointer".
#include <iostream>
using namespace std;
struct CData {
int m_x;
int m_y;
};
int main() {
CData obj = {10, 20};
int CData::*pData = &CData::m_x;
cout << obj.*pData << endl;
return 0;
}
From this example, I am not quire sure when I should use the member variable pointer.
Could you inform me some benefits or example of using the member variable pointer?
Upvotes: 0
Views: 73
Reputation: 20720
I think this is much more useful for functions rather than variable members, but the same principal applies to both.
Say I have a class with 3 functions that do one thing which depends on something such as the processor you are running with (i.e. INTEL versus AMD, or processor that supports SSE4 versus an older process with only SSE2...)
void renderCPU();
void renderSSE2();
void renderSSE3();
void renderSSE4();
Then you'd take the pointer of one of these functions and use the pointer instead of testing whether you have SSE4, SSE3, SSE2, or CPU each time you want to render.
// in constructor
if (SSE4) render_ptr = &C::renderSSE4;
else if (SSE3) render_ptr = &C::renderSSE3;
else if (SSE2) render_ptr = &C::renderSSE2;
else render_ptr = &C::renderCPU;
// And in the render function:
this->*render_ptr();
For variable members, similar things could happen, although frankly I never used that for a variable, probably because you can also use a straight pointer (i.e. an 'int *' in your example...) Although I guess it would be a good idea to use class pointers for added security.
Now, I recall, a while back, using a class with a public const reference pointer to a variable member that was private. In effect, it was giving the user a getter() without having to actually call a function. One problem with that technique is that the reference is locked on construction.
class P
{
private:
int v_;
public:
const int& value;
p()
: value(v_) // locked...
{
}
};
A class variable pointer would allow you to change the pointer while using the object.
class P
{
private:
int x_;
int y_;
int z_;
public:
const int P::*ref;
p()
: ref(&P::x_) // not locked...
{
}
void modeX()
{
ref = &P::x_;
}
void modeY()
{
ref = &P::y_;
}
void modeZ()
{
ref = &P::z_;
}
};
With such a class you should be able to do something like:
P p;
cout << p.*p.ref; // write x_
p.modeZ();
cout << p.*p.ref; // write z_
This makes 'value' quite safe, opposed to a bare pointer.
Note also that gives you the ability to write the following:
P p, q;
p.*q.ref = q.*p.ref;
Which may be useful to some people...
Upvotes: 1