parajulirajesh.com.np

Assignment

A static data member is a variable shared by all objects of a class. static keyword is used to declare the static variable. Only one copy of the variable exists. If one object changes it, all objects see the changed value.

  • Declare inside class
  • Define outside class

    Real-Life Example

    Suppose a school has 500 students.

    • Every student has a different name.
    • But all students belong to the same school.

    The school name is common to all students, so it can be stored as a static data member.

    Syntax

    class ClassName
    {
    public:
    static dataType variableName;
    };

    dataType ClassName::variableName = value;

    Whenever an object is created, the count increases. Since all objects share the same count variable, we use a static data member.

    Program example 1 of using static variable

    #include <iostream>
    using namespace std;

    class Student
    {
    public:
    static int fee; // Declaration
    };

    // Definition
    int Student::fee = 2000;

    int main()
    {
    Student s1, s2;

    cout << “Fee of Student 1 = ” << s1.fee << endl;
    cout << “Fee of Student 2 = ” << s2.fee << endl;

    return 0;
    }

    Example 2

    #include <iostream>
    using namespace std;

    class Student
    {
    public:
    static int count;

    Student()
    {
    count++;
    }
    };

    int Student::count = 0;

    int main()
    {
    Student s1;
    Student s2;
    Student s3;

    cout << “Total Objects = ” << Student::count;

    return 0;
    }

    Output:

    Total Objects = 3

    A static function is a class function that can be called without creating an object.

    Static function is

    • Declared using the static keyword.
    • Belongs to the class, not to objects.
    • Can be called without creating an object.
    • Called using the class name.
    • Can directly access only static data members.

    Syntax of static member function

    class ClassName
    {
    public:
    static void functionName()
    {
    // code
    }
    };

    Calling

    ClassName::functionName();

    Program Example 1:

    A college has a common exam fee for all students. The fee is stored as a static data member, and a static function is used to display it.

     

    #include <iostream>
    using namespace std;

    class Student
    {
    public:
    static int fee; // Static data member

    static void showFee(); // Static function
    };

    int Student::fee = 2000;

    // Definition of static function
    void Student::showFee()
    {
    cout << “Exam Fee = ” << fee;
    }

    int main()
    {
    Student::showFee(); // Calling without object

    return 0;
    }

    Output:

    Exam Fee = 2000

     
Scroll to Top

Rajesh Parajuli

BICTE GMC

LEC.RAJESH PARAJULI

Address: Ghodaghodi Municipality-1 Sukhad kailali

Contact: 9847546279

Ghodaghodi Multiple Campus BICTE