Question
Asked 9th Feb, 2015

What is the role of static function and this pointer in C++?

Please some one explain me in detail about the static function and this pointer in C++?

Most recent answer

1st Apr, 2022
Joel Cameron Adams
Calvin University
Since you are asking about static functions and the this pointer, I'm going to assume that you mean static *methods* (i.e., member functions of a class).
Most object-oriented languages support two kinds of methods:
1) Instance methods are invoked on an instance of a class (i.e., an object). For example, the length() method in class string is an instance method, so it must be invoked on a string object:
std::string str = "hello"; std::cout << str.length();
2) Class methods are invoked on a class. For example, the max() method of the numeric_limits<> template is a class method, so it must be invoked on a class:
std::cout << std::numeric_limits<int>::max();
Instance methods can invoke class methods, but class methods cannot invoke instance methods, nor can class methods access the instance variables of a class.
In C++, declaring a method as static makes it a class method rather than an instance method. Likewise, declaring a data member as static makes it a class member (shared by all instances of the class) rather than an instance member (unique to each instance). I think of class methods and variables as being shared by all instances of the class--as residing at a level 'above' any particular instance/object.
The 'this' pointer is an implicit/hidden parameter that contains the address of the object on which an instance method is invoked. For example, if we have two strings:
std::string str1 = "hello"; std::cout << str1.length();
std:: string str2 = "goodbye"; std::cout << str2.length();
Inside the method-call str1.length(), 'this' contains the address of str1. Inside str2.length(), 'this' contains the address of str2. Since 'this' contains the address of the object on which an instance-method is being invoked, but class methods are not invoked on an object, it follows that 'this' can only be used within instance methods--it doesn't exist within class methods.
If you've written any Python classes / methods, 'this' in C++ is the equivalent of 'self' in Python, but where 'self' is an explicit/required parameter of Python methods, 'this' is an implicit/hidden parameter of C++ methods.

Popular answers (1)

10th Feb, 2015
Simon Schröder
delta h
The 'static' keyword can be used in two different ways. I have to agree with Peter that you should actually distinguish between functions and methods. For free-standing functions, i.e. not in the scope of a class, 'static' means that the function should be inlined by the compiler if possible. In any case the function will be local to the compilation unit (most of the time this is a single cpp-file). This means that your function definition is not visible to other compilation units at link time.
However, in the context of methods 'static' has a completely different meaning. Only in this case it does make sense to talk about the 'this' pointer. The 'this' pointer always points to the current instance of a class, also called an object. It is only available inside of regular member functions (also called methods). These methods can only be called on an object:
class A {
public:
  void foo() {}
};
...
A a;
If you write 'static' in front of a method it will become a class method. Class methods are not related to the object anymore, but to the class. Because there is no object attributed to a class method call the 'this' pointer is not available in this context. You don't even need an object to call class methods:
class B {
public:  static void bar() {}
};
...
B::bar();   // call the method directly
B b;
b.bar();    // also works, but is no different from the previous call
Class methods mostly behave like regular functions declared outside of classes. There is one difference though: You can have 'protected' or 'private' class members (i.e. member variables declared as 'static') which can only be accessed by regular methods and class methods. So, these class member variables are similar to global data, but they are only accessible form functions declared inside the scope of the class.
@Peter: 'static' functions are still allowed in C++. The 'private' keyword is only valid inside of classes/structs. I guess this is to maintain some compatibility to old C code. Unfortunately, 'static' now has two different meanings dependent on the context.
3 Recommendations

All Answers (9)

10th Feb, 2015
Ebenezer R.H.P. Isaac
Ericsson
In the simplest of terms:
A static function is a member function of a class that can be called even when an object of the class is not initialized. A static function cannot access any variable of its class except for static variables.
The 'this' pointer points to the object that invokes the function.
a regular function can access static variables but a static function cannot access regular variables
Illustration:
Suppose you have a class named 'A' with two functions fun1 (regular) and fun2 (static).
#include<iostream>
using namespace std;
class A
{
   static int a;
   int b;
public:
   A(int a, int b) // Constructor
   {
       this->a = a; // this.<var> points to the variable of
       this->b = b; // class A while <var> is a formal parameter
   }
   void fun1()
   {
       cout << a << endl; // Acceptable
       cout << b << endl; // Acceptable
   }
   static void fun2()
   {
       cout << a << endl; // Acceptable
       cout << b; // Error!
   }
};
int A::a = 0; // Initialization of static variable 'a'
int main()
{
   A obj(1,2);
   obj.fun1(); // Allowed
   obj.fun2(); // Allowed
   A.fun1(); // Error!
   A::fun2(); // Allowed
}
I have attached the corrected sample program along with this answer so you may take a look into it and try executing it yourself.
1 Recommendation
10th Feb, 2015
Simon Schröder
delta h
The 'static' keyword can be used in two different ways. I have to agree with Peter that you should actually distinguish between functions and methods. For free-standing functions, i.e. not in the scope of a class, 'static' means that the function should be inlined by the compiler if possible. In any case the function will be local to the compilation unit (most of the time this is a single cpp-file). This means that your function definition is not visible to other compilation units at link time.
However, in the context of methods 'static' has a completely different meaning. Only in this case it does make sense to talk about the 'this' pointer. The 'this' pointer always points to the current instance of a class, also called an object. It is only available inside of regular member functions (also called methods). These methods can only be called on an object:
class A {
public:
  void foo() {}
};
...
A a;
If you write 'static' in front of a method it will become a class method. Class methods are not related to the object anymore, but to the class. Because there is no object attributed to a class method call the 'this' pointer is not available in this context. You don't even need an object to call class methods:
class B {
public:  static void bar() {}
};
...
B::bar();   // call the method directly
B b;
b.bar();    // also works, but is no different from the previous call
Class methods mostly behave like regular functions declared outside of classes. There is one difference though: You can have 'protected' or 'private' class members (i.e. member variables declared as 'static') which can only be accessed by regular methods and class methods. So, these class member variables are similar to global data, but they are only accessible form functions declared inside the scope of the class.
@Peter: 'static' functions are still allowed in C++. The 'private' keyword is only valid inside of classes/structs. I guess this is to maintain some compatibility to old C code. Unfortunately, 'static' now has two different meanings dependent on the context.
3 Recommendations
9th Aug, 2015
Hossein Afshari
Nexthink SA
static function/variables in C++ Class can be accessed with out needing to instantiate an element from the Class. The this pointer point to the object it self. On common example usage of the this is  when you want to return the reference of the object.
1 Recommendation
29th Dec, 2015
Hugh Jensen Mclarty
SpikeLabs
Please, before posting such a question here, did you google "what is a static function in C++" and "this pointer in C++"  Or search Stackoverflow with those questions?
Or if you want to know something more specific, don't make us guess - edit your question to be more specific.
I don't think individuals on RG should be taking time to answer basic questions that have extensive and easily found answers on the internet.
1 Recommendation
20th Mar, 2018
Mohamed Yehia Dahab
King Abdulaziz University
static modifier is for life time of an object or a variable. if the variable inside a function the variable becomes history sensitive.
1st Apr, 2022
Shruti Chamare
Vishwakarma Institute Of Information Technology, Pune
If that static we want to use for life time purposenot changing parameter and that point we can use it
1st Apr, 2022
Joel Cameron Adams
Calvin University
Since you are asking about static functions and the this pointer, I'm going to assume that you mean static *methods* (i.e., member functions of a class).
Most object-oriented languages support two kinds of methods:
1) Instance methods are invoked on an instance of a class (i.e., an object). For example, the length() method in class string is an instance method, so it must be invoked on a string object:
std::string str = "hello"; std::cout << str.length();
2) Class methods are invoked on a class. For example, the max() method of the numeric_limits<> template is a class method, so it must be invoked on a class:
std::cout << std::numeric_limits<int>::max();
Instance methods can invoke class methods, but class methods cannot invoke instance methods, nor can class methods access the instance variables of a class.
In C++, declaring a method as static makes it a class method rather than an instance method. Likewise, declaring a data member as static makes it a class member (shared by all instances of the class) rather than an instance member (unique to each instance). I think of class methods and variables as being shared by all instances of the class--as residing at a level 'above' any particular instance/object.
The 'this' pointer is an implicit/hidden parameter that contains the address of the object on which an instance method is invoked. For example, if we have two strings:
std::string str1 = "hello"; std::cout << str1.length();
std:: string str2 = "goodbye"; std::cout << str2.length();
Inside the method-call str1.length(), 'this' contains the address of str1. Inside str2.length(), 'this' contains the address of str2. Since 'this' contains the address of the object on which an instance-method is being invoked, but class methods are not invoked on an object, it follows that 'this' can only be used within instance methods--it doesn't exist within class methods.
If you've written any Python classes / methods, 'this' in C++ is the equivalent of 'self' in Python, but where 'self' is an explicit/required parameter of Python methods, 'this' is an implicit/hidden parameter of C++ methods.

Similar questions and discussions

Related Publications

Article
Full-text available
The efficiency of object-oriented programs has become a point of great interest. One necessary factor for program efficiency is the optimization techniques involved. This paper presents the performance of several variations of a given C++ program and compares them with a version that uses no object-oriented features. Our result indicates that some...
Chapter
In the five previous chapters, you learned how to code functions that exploited the computational capabilities of AVX and AVX2 using C++ SIMD intrinsic functions. The chapter you are about to read introduces AVX-512 SIMD programming. It begins with a brief overview of AVX-512 and its various instruction set extensions. This is followed by a section...
Got a technical question?
Get high-quality answers from experts.