 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to initialize private static members in C++?
Here we will see how to initialize the private static member variables initialization in C++. We can put static members (Functions or Variables) in C++ classes. For the static variables, we have to initialize them after defining the class.
To initialize we have to use the class name then scope resolution operator (::), then the variable name. Now we can assign some value.
The following code will illustrate the of static member initializing technique.
Example
#include <iostream> using namespace std; class MyClass{    private:       static int st_var;    public:       MyClass(){          st_var++; //increase the value of st_var when new object is created       }       static int getStaticVar() {          return st_var;       } }; int MyClass::st_var = 0; //initializing the static int main() {    MyClass ob1, ob2, ob3; //three objects are created    cout << "Number of objects: " << MyClass::getStaticVar(); }  Output
Number of objects: 3
Advertisements
 