RSS Forums RSS
Please support our C++ advertiser: Programming Forums

pointer to member?

Join Date: Aug 2004
Location: Bozeman MT
Posts: 13
Reputation: glSuccinct is an unknown quantity at this point 
Rep Power: 5
Solved Threads: 1
glSuccinct's Avatar
glSuccinct glSuccinct is offline Offline
Newbie Poster

Re: pointer to member?

  #3  
Aug 12th, 2004
Off the top of me head:
#include <iostream>
#include <conio.h>

using std::cout;
using std::endl;

struct TData
{
	float fWeight;
	float fLength;
};

typedef float (TData::*TDataFloatPointer); // pointer to member

float CalcAverage(const TData* pArray, int iSize, TDataFloatPointer p)
{
	float fAverage = 0;
	for(int i = 0; i < iSize; ++i)
	{
		float f = pArray->*p; // derefernce through the pointer to member
		fAverage += f;
		++pArray;
	}

	return fAverage/iSize;
}

void PrintArrayData(const TData* pArray, int iSize, TDataFloatPointer p)
{
	float fAverage = CalcAverage(pArray, iSize, p);

	for(int i = 0; i < iSize; ++i)
		cout << pArray++->*p << endl;

	cout << "Average:" << endl << fAverage << endl;
}

int main()
{
	const TData vData[] =
	{
		{ 1.0f, 10.0f },
		{ 2, 9 },
		{ 3, 8 },
		{ 4, 7 },
		{ 5, 6 },
		{ 6, 5 },
		{ 7, 4 },
		{ 8, 3 },
		{ 9, 2 },
		{ 10, 1 }
	};
	const NUM_DATA = sizeof(vData)/sizeof(vData[0]);

	cout << "Weights:" << endl;
	PrintArrayData(vData, NUM_DATA, &TData::fWeight); // get the pointer to member

	cout << "Length:" << endl;
	PrintArrayData(vData, NUM_DATA, &TData::fLength);

	getch();
}
Using a pointer to member construct, this will collect each member's weight or length and return an average.

Pointers to members are a niche type of programing mechanism. There are very few instances where pointers to members are even useful, but the times they are, they're invaluable. They're most useful, in my experince, in certain forms of automation, such as running the same algorithm over different members of the same type. Thus particular example could be boiled down to about 10 lines of code were I to go further w/ the pointers to members and templates, but this is a much more clear example.

Hope it helps!
-don't listen to me-
Reply With Quote  
Forums | Blogs | Tutorials | Code Snippets | Whitepapers | RSS Feeds | Advertising
All times are GMT -4. The time now is 2:42 am.
Newsletter Archive - Sitemap - Privacy Statement - Acceptable Use Policy - Contact Us
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC