Difference between static and constant function in C++
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++
// C++ program to illustrate the use // of static function #include "bits/stdc++.h" using namespace std; class A { public : static void f() { cout << "w3wiki!" ; } }; // Driver Code int main() { A::f(); } |
w3wiki!
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++
// C++ program to illustrate the use // of const keyword #include <iostream> using namespace std; // Driver Code int main() { const double a = 1; // Using the below line of code // gives error // a = 2.21; cout << a << endl; return 0; } |
1
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. |