29.6 Pointers to Members

I l @ ve RuBoard

29.6 Pointers to Members

The operator ::* is used to point to a member of a class. For example, in the following code we declare data_ptr as a "pointer to an integer in sample":

 class sample {     public:         int i;    // A couple of member variables         int j; }; int sample::* data_ptr; 

Now data_ptr can point to either the i or the j member of sample . (After all, they are the only integer members of sample .)

Let's set data_ptr so it points to the member i :

 data_ptr = &sample::i; 

An ordinary pointer identifies a single item. A member pointer identifies a member but does not identify an individual variable. All we've done is set data_ptr to a member of sample . data_ptr does not point to a particular integer.

To use data_ptr you need to tell it which object you want:

 sample a_sample; // A typical sample sample b_sample; std::cout << a_sample.*data_ptr << '\n'; std::cout << b_sample.*data_ptr << '\n'; 

The line:

 std::cout << a_sample.*data_ptr << '\n'; 

tells C++ that we want to print an element of the variable a_sample . The variable data_ptr points to an integer member of sample . (The members i and j are our only two integer members.)

There is a shorthand notation for use with class pointers as well:

 sample *sample_ptr = &sample1; std::cout << sample_ptr->*data_ptr << '\n'; 

The syntax for pointers to members is a little convoluted and not terribly useful. I've only seen it used once by an extremely clever programmer. (The first maintenance programmer who got the code immediately ripped it out anyway.)

I l @ ve RuBoard


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net