this pointer?In C++, every non-static member function has access to a special pointer called this, which points to the current object (i.e., the object calling the function). Using this, you can access non-static (instance) members.
this or Access Non-Static Members?Because static member functions are not tied to any object β they belong to the class, not to an instance.
So:
ClassName::function().this pointer, and no way to access members that belong to an object.cpp
CopyEdit
#include <iostream>
using namespace std;
class Demo {
int x; // non-static data member
static int y; // static data member
public:
Demo(int val) : x(val) {}
static void show() {
// cout << x; β Error: Can't access non-static member
// cout << this->x; β Error: No 'this' pointer in static function
cout << "Static function called.\\n";
cout << "Static y = " << y << endl; // β
OK
}
};
int Demo::y = 5;
int main() {
Demo::show(); // Called using class name
return 0;
}
x or this->xYouβll get a compile-time error like:
sql
CopyEdit
error: invalid use of member 'x' in static member function
error: invalid use of 'this' in static member function
| Concept | Static Function | Non-Static Function |
|---|---|---|
| Belongs to | Class | Object |
| Access static data? | β Yes | β Yes |
| Access non-static? | β No | β Yes |
Uses this pointer? |
β No | β Yes |