এখানে লক্ষ্য হল একটি ক্লাসের অবজেক্ট কতটি তৈরি হয়েছে তা স্ট্যাটিক মেম্বার ফাংশন দিয়ে গণনা করা।
স্ট্যাটিক ডেটা মেম্বার ক্লাসের সব অবজেক্টের জন্য শেয়ার্ড হয়। কোনো মান না দিলে স্ট্যাটিক ডেটা মেম্বার সবসময় ০ দিয়ে ইনিশিয়ালাইজ হয়। স্ট্যাটিক মেম্বার ফাংশন শুধু সেই ক্লাসের স্ট্যাটিক ডেটা মেম্বার ব্যবহার করতে পারে।
এখানে Student ক্লাস ব্যবহার করা হয়েছে। count নামে স্ট্যাটিক ডেটা মেম্বার থাকবে যা অবজেক্টের সংখ্যা রাখবে। rollCall() নামে স্ট্যাটিক মেম্বার ফাংশন থাকবে যা অবজেক্টের সংখ্যা রোল নম্বর হিসেবে দেখাবে।
অ্যাপ্রোচ
- Student ক্লাসে public ডেটা মেম্বার int rollno এবং static int count।
- কনস্ট্রাক্টর rollCall() কল করে এবং rollno-কে count দিয়ে ইনিশিয়ালাইজ করে।
- ডিস্ট্রাক্টর count কমিয়ে দেয়।
- স্ট্যাটিক মেম্বার ফাংশন rollCall() অবজেক্টের সংখ্যা Student count হিসেবে দেখায় এবং count বাড়ায়।
- প্রতিবার Student অবজেক্ট তৈরি হলে কনস্ট্রাক্টর rollCall() কল করে, count বাড়ে। এই count সেই অবজেক্টের rollno-তে আসাইন হয়।
- মেইন-এ ৪টি Student অবজেক্ট (stu1, stu2, stu3, stu4) তৈরি করে count এবং rollno যাচাই করা হয়।
উদাহরণ কোড
// C++ program to Count the number of objects
// using the Static member function
#include <iostream>
using namespace std;
class Student {
public:
int rollno;
static int count;
public:
Student() {
rollCall();
rollno = count;
}
~Student() { --count; }
static void rollCall(void) {
cout << endl << "Student Count:" << ++count << "\n";
}
};
int Student::count;
int main() {
Student stu1;
cout << "Student 1: Roll No:" << stu1.rollno;
Student stu2;
cout << "Student 2: Roll No:" << stu2.rollno;
Student stu3;
cout << "Student 3: Roll No:" << stu3.rollno;
Student stu4;
cout << "Student 4: Roll No:" << stu4.rollno;
return 0;
}
আউটপুট
Student Count:1 Student 1: Roll No:1 Student Count:2 Student 2: Roll No:2 Student Count:3 Student 3: Roll No:3 Student Count:4 Student 4: Roll No:4