Pages

Sunday, May 11, 2025

Static Keyword - Static Variable in OOPs (02)

 #include <iostream>

using namespace std;

class Example {
public:
    static int x; // remember to do it const, only way makes it work

};

int Example::x = 0;  // now main func, will share this same object of x.

int main() {
    Example eg1;
    Example eg2;
    Example eg3;
   
    cout << eg1.x++ << endl; // 0
    cout << eg2.x++ << endl; // 1
    cout << eg3.x++ << endl; // 2


    return 0;
}

No comments:

Post a Comment

Stack using Linked List – Partial (University Exam Topic)

 #include <iostream> using namespace std; struct Node {     int data;     Node* next; }; class Stack {     Node* top; public:     Stac...