Static data member in C++ with Example

Learn: What is static data member in C++ programming? How to declare, define static data members and how to access with, without members function in C++?

When we declare a normal variable (data member) in a class, different copies of those data members create with the associated objects.

In some cases when we need a common data member that should be same for all objects, we cannot do this using normal data members. To fulfill such cases, we need static data members.

In this post, we are going to learn about the static data members and static member functions, how they declare, how they access with and without member functions?

C++ static data member

It is a variable which is declared with the static keyword, it is also known as class member, thus only single copy of the variable creates for all objects.

Any changes in the static data member through one member function will reflect in all other object’s member functions.

Declaration

static data_type member_name;

Defining the static data member
It should be defined outside of the class following this syntax:

data_type class_name :: member_name =value;

If you are calling a static data member within a member function, member function should be declared as static (i.e. a static member function can access the static data members)

Consider the example, here static data member is accessing through the static member function:

#include <iostream>
using namespace std;

class Demo
{
	private:	
		static int X;

	public:
		static void fun()
		{
			cout <<"Value of X: " << X << endl;
		}
};

//defining
int Demo :: X =10;


int main()
{
	Demo X;

	X.fun();
	
	return 0;
}

Output

Value of X: 10

Accessing static data member without static member function

A static data member can also be accessed through the class name without using the static member function (as it is a class member), here we need an Scope Resolution Operator (SRO) :: to access the static data member without static member function.

Syntax:

class_name :: static_data_member;

Consider the example:

#include <iostream>
using namespace std;
class Demo
{
	public:	
		static int ABC;
};

//defining
int Demo :: ABC =10;


int main()
{
    
	cout<<"\nValue of ABC: "<<Demo::ABC;
	return 0;
}

Output

Value of ABC: 10

In above program ABC is a class member (static data member), it can directly access with help on scope resolution operator.

Note: The const data member of class is static by default.


Related Tutorials



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.