πŸ” What is 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.

❌ Why Static Member Functions Can’t Use 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:


πŸ’‘ Let’s See With Example

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;
}


❗ If You Try to Access x or this->x

You’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


βœ… Summary

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