C++ Class static member

Introduction

We can define static class member fields.

Static class members are not part of the object.

They live independently of an object of a class.

We declare a static data member inside the class and define it outside the class only once:

#include <iostream> 

class MyClass //  w  w w.ja  va2  s .c  o m
{ 
public: 
    static int x; // declare a static data member 
}; 

int MyClass::x = 123; // define a static data member 

int main() 
{ 
    MyClass::x = 456; // access a static data member 
    std::cout << "Static data member value is: " << MyClass::x; 
} 

Here we declared a static data member inside a class.

Then we defined it outside the class.

When defining a static member outside the class, we do not need to use the static specifier.

Then, we access the data member by using the MyClass::data_member_name notation.

To define a static member function, we prepend the function declaration with the static keyword.

The function definition outside the class does not use the static keyword:

#include <iostream> 

class MyClass //from  w w  w  .ja  va2 s .  co  m
{ 
public: 
    static void myfunction(); // declare a static member function 
}; 
// define a static member function 
void MyClass::myfunction() 
{ 
    std::cout << "Hello World from a static member function."; 
} 

int main() 
{ 
    MyClass::myfunction(); // call a static member function 
} 



PreviousNext

Related