Programmingoneonone is known for sharing best programming knowledge.

static member function in c++ programming

In this post, you will learn about the static member function in c++ programming and learn why we use static data member and member function in programming. 

static member function in c++ programming, learn c++ programming
learn c++ programming


static member function:

the function which can only access the static data member is called the static member function. 

to declare a static data member we just need to use the static keyword at the beginning of the initialize time of the member function. 

Example:
                class test
                {

                   static int function(void);
                }

Note: static function only access the static data members. it does not access the usual members. 

calling the static member function:

we can also call the static member function using the class name. 
Example:
                in the above example, we declare a static member function name function. so to call the static function by class we call like this.


syntext:
             <class-name>::<function-name>;

Example:
              test::function();


Example program for declaring a static data member or a static member function. 

          #include<iostream>

          class test
          {
               int var;

               static int count; 
           // declare a static variable count


               public: 

                      void setval(void);
                      void printval(void);
                      static void printsta(void); 
                
              // declare a static member function.
        
         };


          int test::count;

          void test::setval()
          {
             var= ++count;
          }

         void test::printval()
         {
              std::cout<<"object number:"<< var;
         }

         void test::printsta() //define a static member funtion. 
         {
           std::cout<<"\ncounter"<<count; //only use static variable 
         }

         int main()
         {
             test t1,t2;
             t1.setval();
             t2.setval();

             test::printsta();

             test t3;
             t3.setval();

             test::printsta();
             t1.printval();
             test::printsta();
             t2.printval();
             test::printsta();
             t3.printval();
             test::printsta();

             return 0;
         }


Note: here in the above example we can only access the static data member in the static member function.

"Please share this knowledge as much possible as you can and also comment me your queries and questions related to this topic. I will really grateful to help you."

No comments:

Post a Comment