+ 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.
3 odpowiedzi
+ 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;
}
0
Use the search function.
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.