In C++, the static keyword is used to define members or functions that belong to the class itself rather than to any specific instance of the class. This means that static members are shared among all instances of the class and can be accessed without creating an object of the class.
1. Memory Efficiency: Since static members belong to the class rather than to individual instances, only one copy of a static member exists, regardless of the number of objects created. This saves memory, especially for data that is common to all instances.
2. Access Without Instantiation: Static members can be accessed using the class name directly, without needing to instantiate the class. This can be particularly useful for utility functions or constants that do not depend on object state.
A static field (or static member variable) is a class-level variable that is shared across all instances of the class. Unlike non-static fields, which have separate copies for each object, a static field has a single copy that is shared by all objects of the class.
Single Copy: Only one copy of the static field is created, no matter how many objects of the class are instantiated.
Shared Across Objects: The static field is accessible to all instances of the class, and modifications to it are reflected across all instances.
Access: Static fields can be accessed using the class name or through an object.
<#include <iostream>>
<using namespace std;>
class Account {
private:
static double interestRate; // Static field
public:
// Static method to set interest rate
static void setInterestRate(double rate) {
interestRate = rate;
}
// Static method to get interest rate
static double getInterestRate() {
return interestRate;
}
// Method to display interest rate
void displayInterestRate() {
cout << "Interest Rate: " << getInterestRate()
<< endl;
}
};
// Definition of static field
double Account::interestRate = 0.0;
int main() {
Account::setInterestRate(5.5); // Setting the static field via class name
Account acc1, acc2;
acc1.displayInterestRate(); // Displaying interest rate using object acc1
acc2.displayInterestRate(); // Displaying interest rate using object acc2
return 0;
}
Interest Rate: 5.5
Interest Rate: 5.5