0% found this document useful (0 votes)
86 views15 pages

Static Data Member and Static Data Function

This document discusses static data members and static member functions in C++. Static data members are class members that are shared among all objects of a class, with only one copy existing even if multiple class objects are created. Static member functions can access static data members and other static member functions without needing an object instance. The document provides syntax examples and illustrations of declaring, defining, initializing, and accessing static data members and static member functions in C++.

Uploaded by

bunsbunny1980
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
86 views15 pages

Static Data Member and Static Data Function

This document discusses static data members and static member functions in C++. Static data members are class members that are shared among all objects of a class, with only one copy existing even if multiple class objects are created. Static member functions can access static data members and other static member functions without needing an object instance. The document provides syntax examples and illustrations of declaring, defining, initializing, and accessing static data members and static member functions in C++.

Uploaded by

bunsbunny1980
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 15

Static Data Member

&
Static Member Functions
==================================================================================

Static Data Member:


• Static data member in C++ is a class member that is shared by all objects of the class.
• There is only one copy of a static data member, even if multiple objects of the class are
created.
• Static data members are initialized before any object of the class is created.

Syntax:

The syntax for declaring a static data member is as follows:

static data_type data_member_name;

where data_type is the type of the data member and data_member_name is the name of the
data member.

Illustration:

Example 1: The following C++ program demonstrates the use of Static data member in C++:

#include <iostream>
using namespace std;

class MyClass {

public:

// Calling a User Defined Constructor:


MyClass() {
cout << "MyClass constructor called" << endl;
count++; // incrementing count inside the constructor
}
static int count; //declaring Static Data Member.
};

// Initializing static member variable before creation of Any Object


int MyClass::count = 0; //
int main() {
MyClass obj1; // First constructor call, count becomes 1
MyClass obj2; // Second constructor call, count becomes 2
cout << "Accessing Count using Class= " << MyClass::count << endl;
cout << "Accessing Count Using Obj1= " << obj1.count << endl;
cout << "Accessing Count Using Obj2= " << obj2.count << endl;

return 0;
}

Output:
MyClass constructor called
MyClass constructor called
Accessing Count using Class= 2
Accessing Count Using Obj1= 2
Accessing Count Using Obj2= 2

Explanation:

In the above program:

• The count data member is a static data member of the MyClass class.
• This means that there is only one copy of the count data member, even though two
objects of the MyClass class are created.
• The count data member is initialized to 0 before any object of the MyClass class is
created.

In the main() function:

• Two objects of the MyClass class are created.


• The first object initializes the count data member to 1.
• The second object does not initialize the count data member, because it is already
initialized by the first object.
• Therefore, when the code prints the value of the count data member, it prints the value 2.
Accessing a Static Member in C++
To access a Static data member in C++, we can use either of the following methods:

1. Using a class object:

#include <iostream>
using namespace std;

class A {
public:
static int var; //declaring Static Data Member.
};

int A::var = 5; // Initializing static member variable

int main() {
A obj;

// Access the static data member using the class object


cout << obj.var << endl;

return 0;
}

Output:

2. Using the scope resolution operator (::)


• Static data members can be accessed even without creating an object of the class.
• Here is an example of how to access a static data member without creating an object of
the class using scope resolution operator (::).
Example : Access the static data member using the scope resolution operator
#include <iostream>
using namespace std;

class A {
public:
static int var; //declaring Static Data Member.
};

int A::var = 5; // Initializing static member variable


int main() {
// Access the static data member using the scope resolution
operator
cout << A::var << endl;

return 0;
}

Output:
5

How to Define a Static Data Member


Static data member in C++ are declared by using the static keyword inside the class, but as
they have the lifetime until the program runs and is accessible to every class object they must
be initialized outside the class.

• We initialize static data members after the class declaration and before the main function.
The scope resolution operator is used to access them.
• The memory block of static data members is shared by every object of the class. So, if
there is any change made in the static data member, it will be updated for every other
object of the class.
• Static data member in C++ can be accessed anywhere in the program after the declaration
of class either using the class instance or using scope resolution, class name, and variable
name. There is no need to create objects to access them.

Example: Let’s take an example to see the syntax and to get an idea about initialization:

#include <iostream>
using namespace std;

// creating a class
class myClass{

public:
static int var; // Declaring a Static Data Member

};

// initializing a Static Data Member.


int myClass:: var = 5;

int main()
{
// creating two objects of myClass
myClass obj1, obj2;

cout << "Value of var: " << obj1.var << endl;

// changing value of var by using obj2


obj2.var = 7;

cout << "New value of var: " << obj1.var << endl;
return 0;
}
Output:

Value of var: 5
New value of var: 7

In the above code, we have created a class which consists of a static data member var. Then,
we have initialized var after the declaration of class and before the main function. Take a
look over the syntax for initialization of static data members:

Syntax

data_type class_name :: variable_name = value

• In the main function, we created two objects of class myClass.


• We made the changes in the value of the var by one object and showed that by another
object.
Static Member Functions:
• As we have discussed about the static data members, similarly we have static member
functions which are defined using the static keyword.
• Since, we have defined these functions as static, so they consist of class properties
rather than object properties.
• We can access static member functions by using the class name and scope resolution
operator.

Syntax:

Class_name :: function_name()

As we can call static member function by just using class name and function name, they
can be called even if no object of class be created.

A static member function can only access:

• Static data members,


• other static member functions, and
• any other functions from outside the class.

Let’s see the example of static data members to get a better understanding of it:

#include <iostream>
using namespace std;

// creating a class
class myClass{
public:
static int var;

// defining static function


static int get_val()
{
return var;
}

};

// initializing static data member


int myClass:: var = 5;

int main()
{
// calling static member function
// object of this class is not created yet
cout << "Print the value of var: " << myClass::get_val() << endl;
return 0;
}

Output:
Print the value of var: 5

Explanation of Code:

• In the above code, we have created a class that consists of static data and static function
members.
• Then we have initialized the static data member before the main function.
• In the main function using the static member function printed the value of var without
even creating the object of our class myClass.

The reason we need Static member function:


• Static members are frequently used to store information that is shared by all objects in a
class.
• For instance, you may keep track of the quantity of newly generated objects of a specific
class type using a static data member as a counter. This static data member can be
increased each time an object is generated to keep track of the overall number of objects.
Example: To count the total No of Objects Created
#include <iostream>
using namespace std;

class MyClass {
public:
MyClass() {
cout << "MyClass constructor called" << endl;
count++; // incrementing count inside the constructor
}

static int count;


};

int MyClass::count = 0; // Initializing the static member variable

int main() {
MyClass obj1; // First constructor call, count becomes 1
MyClass obj2; // Second constructor call, count becomes 2

cout << "Count = " << MyClass::count << endl;

return 0;
}

Output:
MyClass constructor called
MyClass constructor called
Count = 2
Example: Public / Private Static Member Variables and Static Member Functions
#include <iostream>
using namespace std;

// creating a class
class myClass{
public:
static int var;
static int get_val()
{
return var1;
}

// defining static function


private:
static int var1;
static int get_val1()
{
return var1;
}

};

// initializing static data member


int myClass:: var = 5;
int myClass:: var1 = 15;

int main()
{
// calling static member function
// object of this class is not created yet
// cout << "Print the value of var: " << myClass::var1 << endl;
cout << "Print the value of var: " << myClass::get_val() << endl;
return 0;
}
Constructor Calling
To initialize the member variables of a class instance or class object there are special member
functions known as constructors.

According to requirements (which member variable we want to initialize), we can define


our own constructors in a class.

Now, if we have a class that consists of a member object, to initialize the object of this class
we will call the constructor that leads to multiple constructor calls. Initially, the
constructors of all member objects are called after that program calls the constructor of the
parent class which consists of all member objects. First, all member objects will be created
and initialized then our complete object will be created and initialized. We will see this with
an example in the next section.

Initialization of Member Objects


As we have discussed the constructors in the above section, we can conclude that the
initialization of an object of any class totally depends upon the constructor.
Let’s take an example to get an idea about initialization.

We will create two classes:

• First Class: First class contains a member variable S with the data type string, a
default constructor, a parameterized constructor, and a copy constructor.
• Second Class: This class contains three member variables, the first one is an integer
variable, second and third both are member objects as they are objects of the first
class. Further, there are two constructors, one is default and another one is
parameterized. At last, there is an initializer list used to initialize all the class data
members at the same time without assigning them values.
• #include <iostream>
• using namespace std;

• // creating first class
• class First{
• public:

• // creating member variable
• string S = "Intial String";

• // default constructor
• First(){
• S = "Default Constructor";
• }

• // parameterized Constructor
• First(string s){
• S = s;
• }

• // Copy Constructor
• First(First &str){
• S = str.S;
• }
• };

• // creating third class
• class Second{
• public:

• // creating member variables
• int A = 1;
• First obj_A;
• First obj_B;

• // defining default constructor
• Second(){
• A = 2;
• obj_A = First();
• obj_B = First("Default value");
• }

• // defining parameterized constructor
• Second(int a, First& obj){
• A = a;
• obj_A = obj;
• obj_B = obj;
• }

• // defining intializer list
• Second(int a, First& obj1, First&
obj2):A{a},obj_A{obj1},obj_B{obj2}
• {
• // no need to assign here
• }
• };

• // function to print the values
• void Print(Second& obj){

• cout << "Value of A: " << obj.A << endl;
• cout << "Value of obj_A String: " << obj.obj_A.S << endl;
• cout << "Value of obje_B String: " << obj.obj_B.S <<
endl;
• cout << endl;
• }

• int main(){

• // creating object of first class
• First A;
• First B("My string");

• // creating objects of second class
• Second obj1;
• Second obj2(3,A);
• Second obj3{4,A,B};

• // printing the values
• cout << "Print values for obj1: \n";
• Print(obj1);
• cout << "Print values for obj2: \n";
• Print(obj2);
• cout << "Print values for obj3: \n";
• Print(obj3);
• return 0;
• }

Output:
Print values for obj1:
Value of A: 2
Value of obj_A String: Default Constructor
Value of obje_B String: Default value

Print values for obj2:


Value of A: 3
Value of obj_A String: Default Constructor
Value of obje_B String: Default Constructor

Print values for obj3:


Value of A: 4
Value of obj_A String: Default Constructor
Value of obje_B String: My string

In the above example, we have taken three cases of initialization of a member object and
object of a class that has a member object.

Case1(obj1) : By using default constructors, created and initialized both object and member
object.
Case2 (obj2) : By using the default constructor for member object and parameterized
constructor, we created and initialized object of the class.

Case3 (obj3) : Used initializer list to initialize both member objects and data object of our
second class. In the above two cases, member objects first call their default constructor for
initialization but in this case, the member object will directly get the value given in the
initializer list and skip the default constructor call.

The above example provides three cases, but there could be many more, totally depending on
the constructors defined by the user.

Has-A Relationship
There are two ways by which a class can use the properties of another class or we can say,
there are two types of relations between classes.

1. Is-A relation: When a class uses the properties of another class by means of
inheritance, then the relation between them is Is-A relation.
2. Has-A relation: When a class uses the properties of another class by having its object
as a member variable, then the relation between them is Has-A relation.

The main motive of both the relations is to re-use the properties to avoid re-declaration.

Conclusion
• Member objects of a class are the class member variables that are objects of another
class that is already defined.
• When a class has a member object, the constructors of the member objects are called
before the constructor of the main class when creating an object. This ensures that the
member objects are initialized first.
• If a class has an object of another class as a member variable that binds them in the
Has-A relation.
• Static members are defined using the static keyword. For static members only once
the memory is allocated.
• Static data member in C++ are declared inside the class but they are initialized outside
of the class.
• Static member functions can be accessed using class name and scope resolution
operator. Also, we can call the member function without creating any object of the
class.

Note:
• https://www.scaler.com/topics/cpp/static-member-in-cpp/

You might also like