×

C++ Static Member Functions



What are static member functions ?

If member function is declared as static then such a function can be called without creating an object of a class .

Syntax :-

ClassName :: functionName (arguments...) ;

Example :-

#include <iostream>
using namespace std;
class Circle {
  public:
    static void area() {
      cout << "Base Class" << endl;
  }
};

int main() {

// No object creation of Class is necessary in case of static functions.
Circle :: area();    

return 0;
}

Output :-

Base class

As you see, member function inside class Circle is static. So you don't have to create an object of that class to call that function. There is another way of calling static functions .

Example 2 :-

#include <iostream>
using namespace std;
class Circle {
  public:
    static void area(int a, int b) {
      out << "Area of circle is " <<3.14 * a * b << endl;
  }
};


int main() {

// No object creation of Class is necessary in case of static functions.
Circle :: area(2,1);    

return 0;
}

Output :-

Area of circle is 6.28