How to Define a Static Data Member of Type const std::string?

In C++, static data members are members that exist independently of any object of the class. A static data member is shared by all objects of the class, meaning there is only one copy of the static member that is shared by all the objects of the class. In this article, we will learn how to define a static data member of type const std::string in C++.

Define a Static Const Data Member in C++

To define a static data member of type const std::string, we have to declare it in the class definition, and initialize it outside the class.

Syntax to Declare a Static Const Data Member

// Declaration in the class definition
static const std::string static_Member_Name;

C++ Program to Define a Static Const Data Member

C++




// C++ Program to illustrate how to Define a Static Data
// Member of Type const std::string
#include <iostream>
#include <string>
using namespace std;
  
class MyClass {
public:
    // declaration of static data member
    static const string str;
};
  
// initialization of static data member
const string MyClass::str = "BeginnerForGeekks";
  
// Driver code
int main()
{
    cout << "Static member value: " << MyClass::str << endl;
    return 0;
}


Output

Static member value: BeginnerForGeekks

As you may have noticed, we have initialized the static const data member after its declaration. It is because static data members cannot be initialized in the class itself. So compiler allows this kind of initialization of a const type.


Contact Us