Czech

g++

Calling non-static function from static funtion


06.08.25

Source Download (6.7kB)

Compiler returns error if we calling from static function non-static function. Following example solving this problem.

We create simple class, which contains static function, non static function and static void pointer to some object.

class CClass
{
	static void *ms_pObject;	///< Void pointer to some object
	
	void NonStaticFunction();
public:
	CClass ();
	~CClass();
	
	static void StaticFunction();
};


Declare static pointer to some object in source file.

void *CClass::ms_pObject;	///< Void pointer to some object

Now in static function cast the void pointer to the class CClass and call by this class non-static function.

void CClass::StaticFunction()
{
	std::cout << "I try call non static function from static function..." << endl;
	// Cast the void pointer
	CClass *pSomeClass = (CClass*)ms_pObject; 
	// Try call non static function
	pSomeClass->NonStaticFunction();
}

void CClass::NonStaticFunction()
{
	std::cout << "Ok... Non static function now calling from static function ..." << endl;
}


home / g++


Valid XHTML 1.0 Transitional