Site icon DataFlair

Static Keyword in C++ Part – 2

Master C++ with Real-time Projects and Kickstart Your Career Start Now!!

Program 1

// Static methods in cpp
#include<iostream>
using namespace std;
class Test
{
    private:
    int n; // non static 
    static string name;
    public:
    Test()
    {
       n=500;
    }
    static void display();
};
string Test::name="Vikas";
void Test::display()
{
    cout<<"Static method of class\n";
    cout<<name;
    //cout<<n;   // non static 
}
int main()
{
    system("cls");
    Test::display();    
    return 0;
}

Program 2

#include<iostream>
using namespace std;
class Test
{
     public:
     static int count;
     Test()
     {
        count++;
     }
   static void display();
};
int Test::count=0;

void Test::display()
{
      cout<<"Total No of Object Created: "<<count;
}

int main()
{
    system("cls");
    Test T1,T2,T3,T4,T5;
    Test::display();
    return 0;
}

Program 3

#include<iostream>
using namespace std;
class MyMath
{
    public:
    static int  factorial(int n);
    static int reverse(int n);
};
int MyMath::factorial(int n)
{
       int f=1;
       while(n!=0)
       {
          f=f*n;
          n--;
       }
       return f;
}
int MyMath::reverse(int n)
{
      int r,s=0;
      while(n!=0)
      {
            r=n%10;
            s=s*10+r;
            n=n/10;
      }
      return s;
}

int main()
{
    system("cls");
    cout<<MyMath::reverse(567);
    return 0;
}
Exit mobile version