static data members and methods in c++

 #include<iostream>

using namespace std;

class Employee {

    int id;
    static int count;
   
    public:

    void setdata(void)
    {
        cout<<"enter the id of the employee ";
        cin>>id;
        count++;
    }
   
    void getdata(void)
    {
        cout<<"the id of the employee is "<<id<<" and the employee number is "<<count<<endl;
    }

    static void getcount(void){
        // cout<<id; this will through and error because id is not a static varibale
        cout<<"the value of count is "<<count<<endl;
    }
    //ye ek static member function hai jo dusre static varibales ya members
    //ya functions ko hi access kar sakta hai other it'll through an error
   
};

int Employee :: count; //default value is 0
//static variables ko class ke bahar declare kiya jata hai
//static function class se related hota hai and use sab functions share karte hai
//isiliye jo count ki value hai vo update hoti gyi har object ke sath vrna same value aate
//for different objects

int main(){

    Employee krishna, shalini, krisha;
    //harry.id = 1;
    //harry.count = 1; will through an error because id and count are private members of employee class
    krishna.setdata();
    krishna.getdata();
    Employee::getcount();

    shalini.setdata();
    shalini.getdata();
    Employee::getcount();

    krisha.setdata();
    krisha.getdata();
    Employee::getcount();

    return 0;
}

Comments

Popular posts from this blog

Function Overloading in C++

oops recall, basic operations and nesting of member functions

OBJECT ORIENTED PROGRAMMING, classes public and private access modifiers (syntax)