Static Member Function in C++The static is a keyword in the C and C++ programming language. We use the static keyword to define the static data member or static member function inside and outside of the class. Let's understand the static data member and static member function using the programs. Static data memberWhen we define the data member of a class using the static keyword, the data members are called the static data member. A static data member is similar to the static member function because the static data can only be accessed using the static data member or static member function. And, all the objects of the class share the same copy of the static member to access the static data. Syntax Here, the static is a keyword of the predefined library. The data_type is the variable type in C++, such as int, float, string, etc. The data_member is the name of the static data. Example 1: Let's create a simple program to access the static data members in the C++ programming language. Output Enter the Id of the Car: 101 Enter the name of the Car: Ferrari Number of the Marks (1 - 10): 10 Id of the Car: 101 Name of the Car: Ferrari Marks: 10 Enter the Id of the Car: 205 Enter the name of the Car: Mercedes Number of the Marks (1 - 10): 9 Id of the Car: 205 Name of the Car: Mercedes Marks: 9 No. of objects created in the class: 2 Static Member FunctionsThe static member functions are special functions used to access the static data members or other static member functions. A member function is defined using the static keyword. A static member function shares the single copy of the member function to any number of the class' objects. We can access the static member function using the class name or class' objects. If the static member function accesses any non-static data member or non-static member function, it throws an error. Syntax Here, the class_name is the name of the class. function_name: The function name is the name of the static member function. parameter: It defines the name of the pass arguments to the static member function. Example 2: Let's create another program to access the static member function using the class name in the C++ programming language. Output The value of the num is: 5 Example 3: Let's create another program to access the static member function using the class' object in the C++ programming language. Output The value of the num is: 15 Example 4: Let's consider an example to access the static member function using the object and class in the C++ programming language. Output Print the static member through object name: The value of the A is: 20 The value of the B is: 30 The value of the C is: 40 Print the static member through the class name: The value of the A is: 20 The value of the B is: 30 The value of the C is: 40
Next TopicConst keyword in C++
|