[C++] pass a class's function to another class

Started by
10 comments, last by MarkusPfundstein 12 years, 6 months ago

So all I need to do is set that function to static. Thanks.
However, I found that I also have to set every variables used in that function to static. That leads to making class B static which leads to unresolved external symbols from static B b[40][40] in another class. I'll try another approach.


No - you can access protected and private class members in a static member function. Consider:


class A {
protected:
int protectedBaseMember;

};

class B : public A {
private:
int privateMember;

static void StaticFunc(A* obj);
};


//static
void B::StaticFunc(A* obj)
{
B* b = (B*)obj;

//this is perfectly legal and accesses two non-static members of B
b->privateMember = b->protectedBaseMember;
}


A static member function can access any member of its class just like a normal member function, but has to do so through a named object rather than the this pointer. All you need to do is make sure the object is properly initialized and arrives in the static function through some means (doesn't need to be passed in as an argument).
Advertisement

class A is a button and class B is "Mine Button" in MineSweeper.


Actually the interesting thing to know is, how do the various B classes differ, and can some of them have several "functionIwantToPass" ?
Assuming they don't, here is a solution:
class A
{
virtual void action() = 0;
public:
void activate() {action();}
};

class B : A
{
void functionIwantToPass() {...}
void action() { functionIwantToPass() }
};


Sorry I you already knew, or if this is not suitable. But I think it is best to learn simple things first, before function pointers.
I show you some code of my project to show you how I solved the problem (ATTENTION: this solution doesn't word with passing parameters to the function pointer. But u can easily implement it)


Declaration:

class AnimatedSprite : public Sprite2D
{




void (BattleEngine::*battlefuncp)();


}


How to initialize it it:

void AnimatedSprite::setEndAnimationFunction(void (BattleEngine::*_pfunc)(), BattleEngine &b)
{
this->battlefuncp = _pfunc;
this->battleEngineUsed = &b;

}

How to call it:
void AnimatedSprite::endOfCurrentAnimationReached()
{
...
(this->battleEngineUsed->*battlefuncp)();
...
}

How to set it: (*this) is here the BattleEngine in which this function is getting called

void BattleEngine::handleInput(){


this->charInFocus>getSprite().setEndAnimationFunction(&BattleEngine::useItem, *this);

..}


hope it helped u. if u have more questions than quote this post please (otherwise i will not see it)

I open sourced my C++/iOS OpenGL 2D RPG engine :-)



See my blog: (Tutorials and GameDev)


[size=2]http://howtomakeitin....wordpress.com/

This topic is closed to new replies.

Advertisement