Home / C++ / Introduction of Static Member
C++ · October 10, 2021

Introduction of Static Member

Static MemberStatic variableStatic variable are initialized to zero before the first object created.Only one copy of static variable exist for a whole program. All object share one copy of static var…

 

Static Member

Static variable

Static variable are initialized to zero before the first object created.

Only one copy of static variable exist for a whole program.

All object share one copy of static variable.

It will remain in the memory till end of the program.

 

Static function

A static function may be called by itself without depending on any object

To access a static function we used,

classname::staticfuction();

 

Example:

#include <iostream>
using namespace std;
 
class statx{
    private:
    int x;
    public:
//here static variable initiate
    static int sum;
//here constructor create
    statx(){
        x=sum++;
    }
//here static function initiate
    static void stat(){
        cout<<"result is "<<sum<<"\n";
    }
    void number(){
        cout<<"Number is: "<<x<<"\n";
    }
};
//here static variable initiate globally
int statx::sum;

int main()
{
   statx o1,o2,o3,o4;
   o1.number();
   o2.number();
   o3.number();
   o4.number();
//here static access without depending on object
   statx::stat();
//here static variable print
   cout<<"static var sum "<<o1.sum;
   return 0;
}

QuantumO0O

Related stories

Back to home →

One briefing. Every Friday.

Nine stories that actually moved the week — machines, markets, science.

Unsubscribe anytime · no spam, ever