Click here to Skip to main content
15,918,471 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I was trying to have an Adapter class, which has a Function Pointer (say fnPtr). And based on different Adaptee classes the fnPtr will be assigned with corresponding adaptee`s function.
Following is the code snippet:
C++
class AdapteeOne
	{
	public:
	int Responce1()
		{
		cout<<"Respose from One."<<endl;
		return 1;
		}
	};
class AdapteeTwo
	{
	public:
	int Responce2()
		{
		cout<<"Respose from Two."<<endl;
		return 2;
		}
	};
class Adapter
	{
	public:
		int (AdapteeOne::*fnptrOne)(void);
		int (AdapteeTwo::*fnptrTwo)(void);
	Adapter(AdapteeOne* adone)
		{
		fnptrOne =  &(AdapteeOne::Responce1);
		this->*fnptrOne();
		}
	Adapter(AdapteeTwo adtwo)
		{
		fnptrTwo =  &(AdapteeTwo::Responce2);
		}
	};
void main()
	{
	Adapter* adpter = new Adapter(new AdapteeOne());

	/////Place to call function pointers of Adapter class

	P;
	}

Now the problem i am facing is in the main() function. I am not getting any way to call Adapter`s function pointers (fnptrOne and fnptrTwo).

Kindly let me know whether this is a correct/viable Adapter pattern?
Posted

1 solution

Your adapter might provide a public method, say execute that in turns uses fnptrOne, or fnptrTwo, based on its internal state (that is on the called ctor at instantiation).
 
Share this answer
 
Comments
Kumar Anitesh 18-Oct-13 4:20am    
Hi Cpallini,
I tried your suggestion:

void Adapter::AdapterExecute()
{
fnptrOne();
}

But i am getting compilation error saying:
error C2064: term does not evaluate to a function taking 0 arguments.
The error statement is very confusing. Please comment.
CPallini 18-Oct-13 4:26am    
The member functions Responce1, Responce2 are not static hence you need an instance of the corresponding object for calling them. That is your adapter should create an instance of the corresponding adaptee class.
Kumar Anitesh 18-Oct-13 5:16am    
Now i wrote the code as:
class Adapter
{
public:
int (AdapteeOne::*fnptrOne)();
int (AdapteeTwo::*fnptrTwo)();
Adapter(AdapteeOne* adone)
{
pAdOne = new AdapteeOne();
fnptrOne = &(pAdOne->Responce1);
}
Adapter(AdapteeTwo adtwo)
{
pAdTwo = new AdapteeTwo();
fnptrTwo = &(pAdTwo->Responce2);
}
void AdapterExecute()
{
fnptrOne();
}
private:
AdapteeOne* pAdOne;
AdapteeTwo* pAdTwo;

};
But, i am getting; error C2276: '&' : illegal operation on bound member function expression; along with the previous error message.
This could mean that '&' operator is not able to create a function pointer out of "pAdOne->Responce1".

Does it mean that we can`t have a function pointer in some ClassA; which could point to a non-static function present in another ClassB?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900