এই পোস্টে, আমরা সি++-এ প্রাইভেট (private) এবং প্রটেক্টেড (protected) অ্যাক্সেস মডিফায়ারের মধ্যে পার্থক্য বুঝব।
প্রাইভেট অ্যাক্সেস মডিফায়ার (Private Access Modifier)
- এগুলো 'private' কীওয়ার্ড দিয়ে ডিক্লেয়ার করা হয়, যার পরে ':' থাকে।
- এগুলো ক্লাসের বাইরে থেকে অ্যাক্সেস করা যায় না।
- 'private' কীওয়ার্ড একটি অ্যাক্সেস মডিফায়ার যা নিশ্চিত করে যে ক্লাসের ভিতরে থাকা ফাংশন এবং অ্যাট্রিবিউটগুলো শুধু সেই ক্লাসের মেম্বাররা অ্যাক্সেস করতে পারে যেন সেগুলো ডিক্লেয়ার করা হয়েছে।
- শুধু মেম্বার ফাংশন বা ফ্রেন্ড ফাংশন (friend functions) 'private' লেবেল করা ডেটা অ্যাক্সেস করতে পারে।
উদাহরণ
#include <iostream>
using namespace std;
class base_class{
private:
string my_name;
int my_age;
public:
void getName(){
cout << "Enter the name... ";
cin >> my_name;
cout << "Enter the age... ";
cin >> my_age;
}
void printIt(){
cout << "The name is : " << my_name << endl;
cout << "The age is: " << my_age << endl;
}
};
int main(){
cout<<"An object of class is created"<< endl;
base_class my_instance;
my_instance.getName();
my_instance.printIt();
return 0;
}
আউটপুট
/tmp/u5NtWSnX5A.o An object of class is created Enter the name... Jane Enter the age... 34 The name is : Jane The age is: 34
প্রটেক্টেড অ্যাক্সেস মডিফায়ার (Protected Access Modifier)
- প্রটেক্টেড অ্যাক্সেস মডিফায়ার প্রাইভেট অ্যাক্সেস মডিফায়ারের অনুরূপ।
- এগুলো 'protected' কীওয়ার্ড দিয়ে ডিক্লেয়ার করা হয়, যার পরে ':' থাকে।
- যে ক্লাস মেম্বার 'Protected' হিসেবে ডিক্লেয়ার করা হয়েছে, সেটি ক্লাসের বাইরে থেকে অ্যাক্সেস করা যায় না।
- সেগুলো সেটি যেখানে ডিক্লেয়ার করা হয়েছে সেটি ক্লাসের ভিতরে থেকে অ্যাক্সেস করা যায়।
- সেগুলো এমন ডেরাইভড ক্লাস (derived class) দিয়েও অ্যাক্সেস করা যায় যার পেরেন্ট ক্লাসে 'protected' মেম্বার থাকে।
- ইনহেরিটেন্স (inheritance) কনসেপ্টের সাথে কাজ করার সময় এগুলো ব্যবহার হয়।
উদাহরণ
#include <iostream>
using namespace std;
class base_class{
private:
string my_name;
int my_age;
protected:
int my_salary;
public:
void getName(){
cout << "Enter the name... ";
cin >> my_name;
cout << "Enter the age... ";
cin >> my_age;
}
void printIt(){
cout << "The name is : " << my_name << endl;
cout << "The age is: " << my_age << endl;
}
};
class derived_class : public base_class{
private:
string my_city;
public:
void set_salary(int val){
my_salary = val;
}
void get_data_1(){
getName();
cout << "Enter the city... ";
cin >> my_city;
}
void print_it_1(){
cout << "The salary is: " << my_salary << endl;
printIt();
cout << "The city is: " << my_city << endl;
}
};
int main(){
cout<<"Instance of derived class is being created.."<<endl;
derived_class my_instance_2 ;
my_instance_2.set_salary(100);
my_instance_2.get_data_1();
my_instance_2.print_it_1();
return 0;
}
আউটপুট
/tmp/u5NtWSnX5A.o Instance of derived class is being created.. Enter the name... Jane Enter the age... 23 Enter the city... NewYork The salary is: 100 The name is : Jane The age is: 23 The city is: NewYork