Saturday, April 19, 2025

C++ OO Static Method in Classes

Static methods are member functions of a class that can be called without creating an instance of the class. They can be accessed using the class name followed by the scope resolution operator ::, without needing to create an object of the class.

Static methods are defined using the static keyword in the class definition and do not have access to non-static member variables or functions of the class. They can only access static member variables and other static member functions. 

Static methods can be used to perform operations that do not depend on the state of an object of the class and can be called without needing to create an instance of the class.


#include <iostream>

using namespace std;

class Cls{
    public:
        static int counter;

        Cls() {
            cout << "Value of Counter Atm: " << ++counter << endl;
        }

        void normalMethod() {
            cout << "Value of Counter Atm: " << ++counter << endl;
        }

        static void staticMethod() {
            cout << "Value of Counter Atm: " << ++counter << endl;
        }
};

int Cls :: counter = 0;

int main() {

    Cls :: staticMethod();
    Cls :: staticMethod();
    Cls :: staticMethod();
    Cls :: staticMethod();

    Cls Obj1;
    Obj1.normalMethod();

    Cls :: staticMethod();

    return 0;
}

This C++ code defines a class named Cls with a static integer variable counter. The class has a constructor that increments the counter variable each time an object of the class is created, and prints the current value of counter to the console. It also has a non-static member function normalMethod that increments the counter variable and prints its current value. In addition, it has a static member function staticMethod that increments the counter variable and prints its current value.

The counter variable is declared as static within the Cls class, so it is shared by all instances of the class. This means that each time the counter variable is incremented, its new value is retained for the next call.

In the main function, the staticMethod of the Cls class is called four times using the class name followed by the scope resolution operator ::. Each call increments the counter variable and prints its current value.

After that, an object of the Cls class named Obj1 is created, which increments the counter variable in its constructor and prints its current value using the normalMethod.

Finally, staticMethod is called again using the class name followed by the scope resolution operator ::, which increments the counter variable and prints its current value.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...