Static member functionscan be used withstatic membervariables in the class. An object of the class is not required to call them.
- The
thispointer does not exist in static member functions because thethis pointerbelongs to the object, whereas static member functions belong to the class, not to the object. In static behavior, we can also call otherstatic data membersandstatic functions.Static member functionscannot be constant.
You can call a
static functionby the object name with thememory access operator (.), but it is not considered good programming practice. It is better to access thestatic member functionof a class by the class name with thescope resolution operator (::).
#include <iostream>
using namespace std;
class Circle
{
int radius;
static const float Pi;
public:
//--------Setter/Mutator------------
void setRadius(int radius)
{
this->radius = radius;
}
int getRadius() const
{
return radius;
}
//-----Getter/Accessor--------------
static int getPi()
{
// Here,you can't access any data member and member function directly except static data member and other static function
// like
// radius=6; -->error
// setRadius(5); -->error
return Pi;
}
};
int main()
{ // Accessing static data member of class through static function with class name and scope resolution operator
cout << Circle::getPi();
}
