Static Member Function in C++ (original) (raw)

Last Updated : 20 Dec, 2022

The static keyword is used with a variable to make the memory of the variable static once a static variable is declared its memory can't be changed. To know more about static keywords refer to the article static Keyword in C++.

Static Member in C++

Static members of a class are not associated with the objects of the class. Just like a static variable once declared is allocated with memory that can't be changed every object points to the same memory. To know more about the topic refer to a static Member in C++.

Example:

class Person{ static int index_number; };

Once a static member is declared it will be treated as same for all the objects associated with the class.

Example:

C++ `

// C++ Program to demonstrate // Static member in a class #include using namespace std;

class Student { public: // static member static int total;

// Constructor called
Student() { total += 1; }

};

int Student::total = 0;

int main() { // Student 1 declared Student s1; cout << "Number of students:" << s1.total << endl;

// Student 2 declared
Student s2;
cout << "Number of students:" << s2.total << endl;

// Student 3 declared
Student s3;
cout << "Number of students:" << s3.total << endl;
return 0;

}

`

Output

Number of students:1 Number of students:2 Number of students:3

Static Member Function in C++

Static Member Function in a class is the function that is declared as static because of which function attains certain properties as defined below:

The reason we need Static member function:

Example:

C++ `

// C++ Program to show the working of // static member functions #include
using namespace std;

class Box
{
private:
static int length; static int breadth;
static int height;

public:

static void print()  
{  
    cout << "The value of the length is: " << length << endl;  
    cout << "The value of the breadth is: " << breadth << endl;  
    cout << "The value of the height is: " << height << endl;  
}

};

// initialize the static data members

int Box :: length = 10;
int Box :: breadth = 20;
int Box :: height = 30;

// Driver Code

int main()
{

Box b;  

cout << "Static member function is called through Object name: \n" << endl;  
b.print();  

cout << "\nStatic member function is called through Class name: \n" << endl;  
Box::print();  

return 0;  

}

`

Output

Static member function is called through Object name:

The value of the length is: 10 The value of the breadth is: 20 The value of the height is: 30

Static member function is called through Class name:

The value of the length is: 10 The value of the breadth is: 20 The value of the height is: 30