Static Keyword

In C++, static is a keyword or modifier that belongs to the type not instance. So instance is not required to access the static members. In C++, static can be field, method, constructor, class, properties, operator and event.

Example

#include <iostream>

using namespace std;


class Account {

   public:

       int accno; // Data member (also instance variable)

       string name; // Data member (also instance variable)

       static float rateOfInterest; // Static member variable


       Account(int accNo, string accName) {

           accno = accNo;

           name = accName;

       }


       // Member function to display account details

       void display() {

           cout << accno << " " << name << " " << rateOfInterest << endl;

       }

};


// Define and initialize the static member variable

float Account::rateOfInterest = 11.2;

int main() {

    Account a1(81901, "Kunal"); // Creating an object of Account

    Account a2(81988, "Kirti");  // Creating another object of Account

    a1.display();

    a2.display();

    return 0;

}


Output

81901 Kunal 11.2

81988 Kirti 11.2


Another example of static keyword in C++ which counts the objects.

#include <iostream>

using namespace std;


class Account {

   public:

       int accno; // Data member (also instance variable)

       string name; // Data member (also instance variable)

       static int count; // Static member variable


       // Constructor to initialize instance variables

       Account(int accNo, string accName) {

           accno = accNo;

           name = accName;

           count++;

       }


       // Member function to display account details

       void display() {

           cout << accno << " " << name << endl;

       }

};


// Define and initialize the static member variable

int Account::count = 0;


int main() {

    Account a1(81901, "Kunal"); // Creating an object of Account

    Account a2(81988, "Kirti");  // Creating another object of Account

    Account a3(81995, "Prabhat"); // Creating an object of Account


    a1.display();

    a2.display();

    a3.display();

    cout<<"Total objects are :"<<Account::count;

    return 0;

}

Output

81901 Kunal 

81988 Kirti 

81995 Prabhat

Total objects are : 3



No comments:

Post a Comment