+ 2

What is static member function? & what is the advantages of it's use in c++ program.

Why we use static member function in program. What is the main advantages of it's over non-static member function.

13th Mar 2017, 6:45 PM
Abhishek Satpathy
Abhishek Satpathy - avatar
3 Réponses
+ 2
Static member functions become useful when you want the class as a whole to have a function, instead of each individual object. With a static member function, you can then change static variable data. For example, a class of cars might have a total count of how many cars you have created: static int nCars; Then you can up the count each time a car is created (in the car constructor) with a static member function: static void CountCars() { Car::nCars++; } ******************************************************* #include <iostream> using namespace std; class Car { public: static int nCars; static void CountCars(); Car() { CountCars(); } }; int Car::nCars = 0; void Car::CountCars() { Car::nCars++; } // you MUST define statics OUTSIDE of the class int main() { Car firstCar; cout << Car::nCars << endl; // outputs 1 Car secondCar; cout << Car::nCars << endl; // outputs 2 return 0; }
13th Mar 2017, 8:30 PM
Zeke Williams
Zeke Williams - avatar
0
Use the search function.
13th Mar 2017, 8:05 PM
1of3
1of3 - avatar
0
Static function: + : it could be called without existing real object - : it doesn't have pointer to real object ("this") For example, "singleton class" (with private constructor) is great example of static function advantage using.
13th Mar 2017, 9:39 PM
Dare-devil
Dare-devil - avatar