Â
Static Operator in C++ :-Â
-->Â Â Static Operator is an operator which does not require any instance to access it members. For example we have a class, now in order to access the class we create an object / instance to access it and its members, but when we create a static class then we don't have to create any object /Â instance for it. It can be directly accessed or called.Â
Static Operator can be used for many things / purposes like there can be a static method (Function), variable or declaration etc.Â
Static functions are accessed using only the class name and the scope resolution operator " :: ".Â
A static member function can only access static data member, other static member functions and any other functions from outside the class.
Syntax To Use Static Operator:
// Static Function
static void fnc_name()
{
// Function_Content
}
// Static Variable
static datatype variable_name
Example to use Static Operator for a function :
/*C++ program to print WELCOME TO HFC!!! */
#include<iostream>
#include<stdlib.h>
using namespace std;
class print
{
public:
static void show(void)
{
cout << "Welcome to HFC!!!";
}
};
int main(void)
{
system("cls");
print::show();
return 0;
}
OUTPUT:-
Example to use Static Operator for a Variable :
//C++ program to call and increment COUNT 3 times.
#include<iostream>
#include<stdlib.h>
using namespace std;
class Class
{
public:
static int count;
Class();
};
Class::Class()
{
count++;
}
int Class::count = 0;
int main(void)
{
system("cls");
cout << "Initial value of count:- " << Class::count;
Class obj1, obj2, obj3;
cout << "\nCount value after 3 objects:- " << Class ::count;
return 0;
}
OUTPUT:-
In this post we got to know about Static Operator and it's uses with function and Variable in C++.
#ENJOY CODING
Post a Comment
FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP