OOP-Weekend Lecture 06
OOP-Weekend Lecture 06
Static data member is a member variable of a class that is associated with class not
objects. Suppose if you create 3 objects of a class there will be only 1 copy of static data
member created.
Task 1
In a company, each employee needs a unique ID number that increments every time a
new employee is created. Write a class Employee that automatically assigns an ID to
each employee starting from 1001 and increments the ID with each new employee.
Display the current employee's ID and the next available ID.
Tasks to Do:
1. Create a static member variable nextId to hold the next available ID (starting from
1001).
2. Create a constructor that assigns the current nextId value to each Employee object
and increments nextId.
3. Add a non-static member function showId() to display the employee's ID.
4. Add a static member function showNextId() to display the next available ID.
5. In main(), create at least 3 employees and display their IDs, as well as the next
available ID.
#include <iostream>
class Employee {
int empId;
public:
Employee() {
empId = nextId++;
}
void showId() {
cout << "Next available ID: " << nextId << endl;
};
int main() {
e1.showId();
e2.showId();
e3.showId();
Employee::showNextId();
return 0;
}
Task 2
Create a class Book that tracks how many books have been borrowed from a library.
Each time a book is borrowed, increment a static counter and display the total number of
borrowed books.
🔧 Tasks to Do:
#include <iostream>
using namespace std;
class Book {
string title;
static int borrowedCount;
public:
Book(string t) : title(t) {}
void borrowBook() {
borrowedCount++;
cout << title << " borrowed." << endl;
}
static void showBorrowedCount() {
cout << "Total books borrowed: " << borrowedCount << endl;
}
};
int Book::borrowedCount = 0;
int main() {
Book b1("1984");
Book b2("Brave New World");
b1.borrowBook();
b2.borrowBook();
Book::showBorrowedCount();
return 0;
}
Task 3
Design a system to track the total number of students that have registered in a university.
Each time a student object is created, the counter should increment. Display the total
number of students registered.
Tasks to Do:
1. Define a static variable registrationCount in the Student class to track the total
number of students.
2. Increment registrationCount in the constructor whenever a new student is created.
3. Implement a static method showRegistrations() to display the total number of
students.
4. In main(), create at least 3 student objects and call showRegistrations() to display
the total count.
#include <iostream>
class Student {
public:
Student() {
registrationCount++;
};
int Student::registrationCount = 0;
int main() {
Student::showRegistrations();
return 0;