In this post, we will see Static Data Member and Static Member Functions in C++ | Static Variables & Methods in C++ OOPS
Program Code: (static1.c)
#include<stdio.h>
void counter()
{
static int x=0;
x=x+1;
printf("Value of x=%d\n",x);
}
int main()
{
counter();
counter();
counter();
}
Program Code: (static1.cpp)
#include<iostream>
using namespace std;
void counter()
{
static int x=0;
x=x+1;
cout<<"Value of x="<<x<<endl;
}
int main()
{
counter();
counter();
counter();
}
Program Code: (static2.cpp)
#include<iostream>
using namespace std;
class Student
{
public:
void counter()
{
static int x=0;
x=x+1;
cout<<"Value of x="<<x<<endl;
}
};
int main()
{
Student s1,s2,s3;
s1.counter();
s2.counter();
s3.counter();
}
Program Code: (static3.cpp)
#include<iostream>
using namespace std;
class Student
{
public:
static int x;
public:
void counter()
{
x=x+1;
cout<<"Value of x="<<x<<endl;
}
};
int Student::x=4;
int main()
{
Student s1,s2,s3;
s1.counter();
s2.counter();
s3.counter();
cout<<"Value of x="<<Student::x<<endl;
}
Program Code: (static4.cpp)
#include<iostream>
using namespace std;
class Student
{
private:
static int x;
int y=4;
public:
void counter()
{
x=x+1;
cout<<"Value of x="<<x<<endl;
}
static void getCount()
{
cout<<"Total number of students="<<x<<endl;
//we can not use non static variable of class inside static function
//cout<<"The value of y="<<y<<endl;
int z=5;
//we can define non static variable inside static function
cout<<"The value of z="<<z<<endl;
Student s;
//we can call non static function inside static function
s.counter();
}
};
int Student::x;
int main()
{
Student s1,s2,s3;
s1.counter();
s2.counter();
s3.counter();
Student::getCount();
}
Watch following video:
Watch on YouTube: https://www.youtube.com/watch?v=7Eg8gNViHZ0
No comments:
Post a Comment