Static Member Example in C++


This code defines a Student class with member variables rollno and name, as well as a static int variable addminNo that keeps track of the next admission number. The constructor initializes the name and rollno member variables, increment the addminNo static variable, and assigns the current value of addminNo to the rollno.

In the main function, two Student objects s1 and s2 are created with names "Ram" and "Sam" respectively, and their display method is called to print their name and roll number. Finally, the addminNo static variable is accessed via the Student class to print the next admission number.

This code demonstrates the use of static member variables to keep track of a value that is shared across all instances of a class. In this case, the addminNo variable is incremented each time a new Student object is created, ensuring that each student gets a unique roll number.

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

Program List


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