Static Member Example in C++


Description:

When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member. A static member is shared by all objects of the class. All static data is initialized to zero when the first object is created, if no other initialization is present.

Example Program:

Here is the simple program static member function in C++.

Source Code

#include<iostream>
//Static Member Variable
using namespace std;
class Student
{
public:
    int rollno;
    string name;
    static int addminNo;
    Student(string n)
    {
        name=n;
        addminNo++;
        rollno=addminNo;
    }
    void display()
    {
        cout<<"Name : "<<name<<" | Roll No : "<<rollno<<endl;
    }
};
int Student::addminNo=0;
int main()
{
    Student s1("Ram");
    s1.display();
    Student s2("Sam");
    s2.display();
    cout<<"Next Admission No  : "<<(Student::addminNo)+1<<endl;
}
/*
Use of static member
Shared memory
provide info about class
*/
To download raw file Click Here

Output

Name : Ram | Roll No : 1
Name : Sam | Roll No : 2
Next Admission No  : 3

Basic Programs


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples



Learn All in Tamil © Designed & Developed By Tutor Joes