954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

what's the difference between using an ordinary pointer and a "pointer to member"?

#include <iostream>
using namespace std;
#define PRINT(x) cout << #x " = " << x << endl;

class Object{
public:
	Object():i(5){}
	 int i;;
};

int main() {
	Object o;
	o.i = 5;
	int* p = &(o.i);
	PRINT(*p);

	int Object::* p2m = &Object::i;
	PRINT(o.*p2m);
	return 0;
}


the two PRINT macros produce this:

*p = 5
o.*p2m = 5


could you tell me what the difference is between using them? when should i choose one over another? and why?
Thank you in advance!

kevintse
Light Poster
38 posts since Nov 2008
Reputation Points: 10
Solved Threads: 1
 

Well ordinarily, your data in the class wouldn't be public to begin with.

Making it public defeats the whole purpose of having classes at all.

Salem
Posting Sage
Team Colleague
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
 

Read about:
- pointers to member functions:
http://www.gidforums.com/t-18332.html
- pointer to data members:
http://www.icce.rug.nl/documents/cplusplus/cplusplus15.html#l219

ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You