Trong bài viết này, chúng ta sẽ hiểu sự khác biệt giữa private và protected access modifiers trong C++.
Private Access Modifier
- Khai báo bằng từ khóa 'private' theo sau là ':'.
- Không thể truy cập bên ngoài lớp.
- Từ khóa 'private' đảm bảo hàm và thuộc tính chỉ được truy cập bởi thành viên của lớp nơi khai báo.
- Chỉ hàm thành viên (member functions) hoặc friend functions mới được truy cập dữ liệu 'private'.
Ví dụ
#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;
}Kết quả
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 tương tự private.
- Khai báo bằng 'protected' theo sau là ':'.
- Thành viên 'protected' không truy cập được bên ngoài lớp.
- Có thể truy cập trong lớp khai báo.
- Cũng có thể truy cập bởi lớp dẫn xuất (derived class) có lớp cha chứa 'protected'.
- Dùng khi làm việc với kế thừa (inheritance).
Ví dụ
#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;
}Kết quả
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