What is Static Data Member in C++
In C++, a static data member is a class variable that is shared by all objects of the class, rather than being unique to each object.
In C++, a static data member is a special type of member variable that is shared among all instances of a class. It is associated with the class itself rather than with individual objects of the class. In this article, we will explore the concept of static data members, their declaration, usage, and the benefits they offer in C++ programming.
Table of Contents
- Static Member Functions
- Examples of Static Members in C++
- Constant Static Members
- Accessing Static Data Member Without Static Member Function
Static data member is defined using the “static” keyword, and it is typically declared within the class definition but outside of any member function. The static data member can be accessed using the class name, rather than an object of the class.
You can also explore: Convert char to int in C++ Using Different Methods
Syntax
The syntax for defining a static data member in a C++ class is as follows:
class ClassName { static type static_member_name; // other members};
Where “ClassName” is the name of the class, “type” is the data type of the static member, and “static_member_name” is the name of the static member.
You can also explore: Member function in C++
Preparing for a C++ interview? Check out the Top C++ Interview Questions and Answers
Also Read – Understanding Operators in C++
Learn more: Basics of C Programming Language
For example, if you want to define a static int member named “count” in a class named “Counter”, the code would look like this:
class Counter { static int count; // other members};
You can also initialize the static member variable inside the class declaration.
class Counter { static int count = 0; // other members};
It’s also important to note that you can only define the static member variable inside the class, but the definition of the variable should be outside the class.
This is so that the variable can be allocated to storage in memory.
You can also explore: Exception handling in C++
Explore popular Programming Courses
Best-suited C++ courses for you
Learn C++ with these high-rated online courses
Static Member Functions
In C++, a static member function is a member function of a class that can be called without creating an object of the class. It is defined using the “static” keyword, and it is typically declared within the class definition but outside of any member function.
A static member function can only access static data members of the class, and it cannot access non-static data members or member functions of the class. It is generally used for utility functions that do not depend on the state of an object.
The syntax for declaring a static member function in a C++ class is as follows:
class ClassName { // other members static return_type function_name(parameter list);};
Where “ClassName” is the name of the class, “return_type” is the return type of the function, “function_name” is the name of the function, and “parameter list” is the list of parameters passed to the function.
You can also explore: C++ Structure and Functions
For example, if you want to define a static member function named “getCount” in a class named “Counter” that returns the current count of objects, the code would look like this:
class Counter { // other members static int getCount();};
You can also define the function outside the class
class Counter { // other members static int getCount();};int Counter::getCount(){ // function body return count;}
A static function can be called using the class name, without the need to create any object of the class.
Counter::getCount();
It’s important to note that, unlike non-static member functions, static member functions do not have access to this pointer and therefore cannot access the non-static members of the class.
You can also explore: Default Arguments in C++
Examples of Static Members in C++
Here are a couple of examples of how static data members can be used in C++:
Example 1: A class representing a bank account that has a static member variable to keep track of the number of account objects created:
class BankAccount { int accountNumber; double balance; static int numberOfAccounts;
public: BankAccount(int accountNumber, double balance); void deposit(double amount); void withdraw(double amount); static int getNumberOfAccounts();};
int BankAccount::numberOfAccounts = 0;
BankAccount::BankAccount(int accountNumber, double balance) { this->accountNumber = accountNumber; this->balance = balance; numberOfAccounts++;}
void BankAccount::deposit(double amount) { balance += amount;}
void BankAccount::withdraw(double amount) { balance -= amount;}
int BankAccount::getNumberOfAccounts() { return numberOfAccounts;}
In the example above, the class BankAccount has a static member variable “numberOfAccounts” which keeps track of the number of account objects created. The static member function “getNumberOfAccounts” returns the value of this variable.
You can also explore: All About C++ Friend Function
Example 2: A class representing a car that has a static member variable to keep track of the total distance traveled by all car objects:
class Car { int id; double mileage; static double totalDistance;
public: Car(int id); void drive(double distance); double getMileage(); static double getTotalDistance();};
double Car::totalDistance = 0;
Car::Car(int id) { this->id = id; mileage = 0;}
void Car::drive(double distance) { mileage += distance; totalDistance += distance;}
double Car::getMileage() { return mileage;}
double Car::getTotalDistance() { return totalDistance;}
In this example, the class Car has a static member variable “totalDistance” which keeps track of the total distance traveled by all car objects. The static member function “getTotalDistance” returns the value of this variable. Each Car object also has a non-static member variable “mileage” that keeps track of the distance traveled by the individual car.
These are just examples, static data members can be used in many different ways, for example for counting the number of instances of a class, for storing shared configuration data among all instances, for implementing singletons, etc.
You can also explore: C++ if else Statement
Constant Static Members
In C++, a constant static member is a static member variable that is declared as “const”, meaning it cannot be modified after it has been initialized. Constant static members are typically used to store values that are common to all objects of a class, but that do not need to be modified. The value of a constant static member must be known at compile-time, and it can be initialized at the point of definition or in the constructor of the class.
The syntax for declaring a constant static member in a C++ class is as follows:
class ClassName { static const type constant_member_name = value; // other members};
Where “ClassName” is the name of the class, “type” is the data type of the constant member, “constant_member_name” is the name of the constant member, and “value” is the constant value.
For example, if you want to define a constant static double member named “pi” in a class named “MathConstant“, the code would look like this:
class MathConstant { static const double pi = 3.14159; // other members};
You can also initialize a constant static variable inside the class declaration.
class MathConstant { static const double pi;};const double MathConstant::pi = 3.14159;
It’s important to note that you can only access constant static members through the class name, not by an object of the class. Also, the value of a constant static member is the same for all instances of the class, and it cannot be modified.
Accessing Static Data Member Without Static Member Function
In C++, you can access a static data member without using a static member function by using the class name and the scope resolution operator (“::”).
Here is an example:
class MyClass { public: static int myStaticData;};
int main() { MyClass::myStaticData = 5; // accessing the static data member std::cout << MyClass::myStaticData << std::endl; // accessing the static data member return 0;}
As you can see, the static data member “myStaticData” is accessed using the class name “MyClass” and the scope resolution operator “::”.
Another way to access a static data member is by using an object of the class, but it will not be recommended since it’s not the purpose of using a static data member.
class MyClass { public: static int myStaticData;};int main() { MyClass obj; obj.myStaticData = 5; // accessing the static data member std::cout << obj.myStaticData << std::endl; // accessing the static data member return 0;}
It’s important to note that, while it is possible to access a static data member using an object of the class, it is generally considered better practice to use the class name and scope resolution operator to access static data members. This makes it clear that the member is shared among all objects of the class, and not specific to any one object.
You can also explore: Introduction to QuickSort Algorithm in C++
Conclusion:
In C++, static data members do not have a separate copy for each object of a class. Instead, only one copy is shared among all instances of the class. These members are declared within the class and defined outside of it. They can be accessed using the scope resolution operator (::) or a static member function. Additionally, constant static data members can be initialized within the class in which they are defined.
FAQs
Can a static data member be accessed through an object of the class?
Although it is possible to access a static data member using an object of the class, it is recommended to access it directly through the class name. Accessing it through an object may lead to confusion, as it suggests that the member is specific to that particular object.
How is the memory allocated for a static data member?
Memory for a static data member is allocated separately from the objects of the class. It is typically allocated in the global or static memory area and remains accessible throughout the program's execution.
How is a static data member declared in C++?
To declare a static data member in C++, you use the static keyword within the class declaration. The static data member is defined outside the class declaration, usually in the implementation file (.cpp), to allocate memory for it.
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio