Code Snippets
C/C++ Code Snippets
C++ program to declare, define and access public static data member.
By: IncludeHelp, On 07 OCT 2016
In this program we will learn how to declare, define and access a public static data member inside main function using class name.
Class’s static data members are the member of class and we can access them by using class name only, they cannot be accessed with the object.
So here we will learn how to declare, define and access a public static data member.
Declaring a static data member
static [data_type] [variable_name];
Defining a static data member
We can define a static data member outside of the class using Scope Resolution Operator (::), here is the syntax
[data_type] [class_name] :: [variable_name];
Accessing a static data member
By using Scope Resolution Operator with the class name we can access any static data member which is public in the class, here is the syntax to access a public data member
[class_name]::[variable_name];
C++ program (Code Snippet) – Declare, Define and Access a Public Static Data Member inside main()
Let’s consider the following example:
/*C++ program to declare, define and access
public static data member.*/
#include <iostream>
using namespace std;
class Sample{
public:
//declaration of static data member
static int x;
};
//defining static data member of class
int Sample::x=0;
int main(){
//accessing static data member
cout<<"value of x: "<<Sample::x<<endl;
//modify the value of x
Sample::x=100;
cout<<"Modified value of x: "<<Sample::x<<endl;
return 0;
}
Output
value of x: 0
Modified value of x: 100