Static Function: It is a member function that is used to access only static data members. It cannot access non-static data members not even call non-static member functions. It can be called even if no objects of the class exist. It is also used to maintain a single copy of the class member function across different objects of the class.
Program 1:
C++
#include "bits/stdc++.h"
using namespace std;
class A {
public :
static void f()
{
cout << "GeeksforGeeks!" ;
}
};
int main()
{
A::f();
}
|
Constant Function: It is a function that is generally declared as constant in the program. It also guarantees that it will not allow modifying objects or call any non-const member functions. It specifies that function is a read-only function and does not modify the object for which it is called.
Program 2:
C++
#include <iostream>
using namespace std;
int main()
{
const double a = 1;
cout << a << endl;
return 0;
}
|
Tabular Difference between static function and constant function:
Static Function
|
Constant Function
|
It is declared using the static keyword. |
It is declared using the const keyword. |
It does not allow variable or data members or functions to be modified again. Instead, it is allocated for a lifetime of the program. |
It allows specifying whether a variable is modifiable or not. |
It helps to call functions that using class without using objects. |
It helps us to avoid modifying objects. |
This function can only be called by static data members and static member functions. |
This function can be called using any type of object. |
It is useful to declare global data which should be updated while the program lives in memory, used to restrict access to functions, reuse the same function name in other files, etc. |
It is useful with pointers or references passed to function, used to avoid accidental changes to object, can be called by any type of object, etc. |
It is a member function that generally allows accessing function using class without using an instance of the class. |
It is a member function that is generally declared as constant in the program. |
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!