Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 26. Other Topics > Pointers to Class Members (.* and ->*)

26.6. Pointers to Class Members (.* and ->*)

Visual C++ provides the .* and ->* operators for accessing class members via pointers. This capability is used primarily by advanced Visual C++ programmers. We provide only a mechanical example of using pointers to class members here. Figure 26.6 demonstrates the pointer-to-class-member operators.

Fig. 26.6. Demonstrating the .* and ->* operators.

					1
					// Fig. 26.6: PointerToClassMember.cpp
					2
					// Demonstrating operators .* and ->*.
					3
					#include <iostream>
 4
					using std::cout;
 5
					using std::endl;
 6
					7
					// class Test definition
					8
					class Test
 9  {
10
					public:
11
					void test()
12     {
13        cout << "In test function\n";
14     } // end function test
					15
					16
					int value; // public data member
					17  }; // end class Test
					18
					19
					void arrowStar( Test * ); // prototype
					20
					void dotStar( Test * ); // prototype
					21
					22
					int main()
23  {
24     Test test;
25     test.value = 8; // assign value 8
					26     arrowStar( &test ); // pass address to arrowStar
					27     dotStar( &test ); // pass address to dotStar
					28
					return 0;
29  } // end main
					30
					31
					// access member function of Test object using ->*
					32
					void arrowStar( Test *testPtr )
33  {
34
					void ( Test::*memPtr )() = &Test::test; // declare function pointer
					35
					( testPtr->*memPtr )(); // invoke function indirectly
					
					36  } // end arrowStar
					37
					38
					// access members of Test object data member using .*
					39
					void dotStar( Test *testPtr2 )
40  {
41
					int Test::*vPtr = &Test::value; // declare pointer
					
					42
					cout << ( *testPtr2 ).*vPtr << endl; // access value
					43  } // end dotStar

					  

In test function
8



  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint