In: Computer Science
Write a C++ program to show the use of static data member and static member_function. Give an explanation of the scenario you used to code (e.g. why it is required to use the static members). Upload only a word document file that contains the exact code and its explanation as asked.
also write comments against each line of code
SOLUTION:-
C++ static data member
Sometime when we need a common data member that should be same for all objects then we need static data members. So, any changes in the static data member through one member function will reflect in all other object’s member functions.
Let's take a program to understand it clearly as -
//necessary header file #include <iostream.h> #include <conio.h> using namespace std; // create a class Stat class Stat { private: //static data member declaration static int X; public: //static member function static void fun() { cout <<"Value of X: " << X << endl; } }; //definition of static data member, it should be always outside the class int Stat :: X = 10; //main function to execute the code int main() { //object of class X Stat X; //accessing the static data member using static member function X.fun(); return 0; }
OUTPUT : Value of X: 10
Case2: Static data member can also be accessed through the class name without using the static member function
#include <iostream> #include <conio.h> using namespace std; class Stat { public: static int X; }; //definition of static data member, it should be always outside the class int Stat :: X =20; int main() { //here we need an Scope Resolution Operator (SRO) :: to access the static data member //without static member function. cout<<"\nValue of X: "<<Stat::X; return 0; }
OUTPUT : Value of X: 20