Can we use THIS Pointer in static function – Reason in C++?

We cannot use THIS pointer in static function of a class in C++ program.

Reason: Whenever we call a class non-static member function using class object then THIS pointer is also passed to the function as a parameter internally and this is why a non-static member function of a class know that on which class object it is being called in case of multiple objects creation of the class.

Recommended: How does “this” pointer in C++ work internally?

But, static function of a class is not associated with class object. So, THIS pointer is not passed to a static function as an internal parameter. So, a static function does not understand THIS pointer inside its body.

If we compile below class, compiler with throw an error i.e. static functions do not have this pointer.

class Printer{
	static int a;
public:
	static void print(){
		//Error static funtions do not have 
		//this pointer.
		this->a; 
	}
};

This is why static member function cannot have this pointer in C++ language.

Related Posts