What is static function in cpp? Is it same as in C?

Answer:

C++ Static function is the function that is independent of an object of the class.  And called by class name and scope resolution :: operator without creating any object.

However, there is no harm calling static functions using object, but that is redundant and may be confusing to developers in a large project as it gives impression that it is non static function in client code and considered a bad practice.

Also, static function doesn’t understand ‘this’ pointer as it is independent of objects.

C++ code example

class A
{
	int a;
public:	
	static void func1()//static function
	{
		//this->a =2;	//Error: static member functions do not have 'this' pointer
	}

	void func2()//non static function
	{
		this->a =2; //OK
	}
};
int main()
{
	A::func1(); //static function call
	
	A ob;
	ob.func1(); //static function can be called using object, but no ‘this’ pointer is passed to it internally.
}

C:

No, C++ static function is not same as in C. The Static function in C is used for local linkage.

Related Posts