
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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
Defining static members in C++
Static members in a class in C++ can be defined using the static keyword. There is only one copy of the static class member in memory, regardless of the number of objects of the class. So the static member is shared by all the class objects.
The static class member is initialized to zero when the first object of the class is created if it is not initialized in any other way.
A program that demonstrates the definition of the static class members is given as follows −
Example
#include <iostream> using namespace std; class Point{ int x; int y; public: static int count; Point(int x1, int y1){ x = x1; y = y1; count++; } void display(){ cout<<"The point is ("<<x<<","<<y<<")\n"; } }; int Point::count = 0; int main(void){ Point p1(10,5); Point p2(7,9); Point p3(1,2); p1.display(); p2.display(); p3.display(); cout<<"\nThe number of objects are: "<<Point::count; return 0; }
The output of the above program is as follows −
The point is (10,5) The point is (7,9) The point is (1,2) The number of objects are: 3
Now let us understand the above program.
The class Point has 2 data members x and y that constitute a point. There is also a static member count that monitors the numbers of objects created of class Point. The constructor Point() initializes the values of x and y and the function display() displays their values. The code snippet that shows this is as follows −
class Point{ int x; int y; public: static int count; Point(int x1, int y1){ x = x1; y = y1; count++; } void display(){ cout<<"The point is ("<<x<<","<<y<<")\n"; } };
In the function main(), there are 3 objects created of class Point. Then the values of these objects are displayed by calling the function display(). Then the value of count is displayed. The code snippet that shows this is as follows −
Point p1(10,5); Point p2(7,9); Point p3(1,2); p1.display(); p2.display(); p3.display(); cout<<"\nThe number of objects are: "<<Point::count;
- Related Questions & Answers
- Static Data Members in C++
- Static Members in Ruby Programming
- When are static C++ class members initialized?
- How to initialize private static members in C++?
- What are static members of a C# Class?
- What are static members of a Java class?
- Comparing enum members in C#
- What are the steps to read static members in a Java class?
- Private and Protected Members in C++
- Are array members deeply copied in C++?
- Static vs. Non-Static method in C#
- Can a "this" keyword be used to refer to static members in Java?
- Flexible Array Members in a structure in C
- Defining Colors in CSS3
- Defining Keyframes in CSS3