C++에서 접근 제한자(access modifier)는 클래스 내부의 멤버 변수와 함수에 대한 외부 접근 범위를 결정하는 중요한 개념입니다. 이 글에서는 private과 protected 두 가지 접근 제한자의 차이점을 예제 코드와 함께 자세히 살펴보겠습니다.
private 접근 제한자란?
- 'private' 키워드 뒤에 ':'(콜론)을 붙여 선언합니다.
- 클래스 외부에서는 접근할 수 없습니다.
- private으로 선언된 멤버는 해당 멤버가 선언된 클래스의 멤버만 접근할 수 있도록 보장합니다.
- private 데이터에는 오직 멤버 함수 또는 프렌드(friend) 함수만 접근이 허용됩니다.
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;
}실행 결과
An object of class is created Enter the name... Jane Enter the age... 34 The name is : Jane The age is: 34
위 예제에서 my_name과 my_age는 private으로 선언되었기 때문에 getName(), printIt() 같은 public 멤버 함수를 통해서만 접근할 수 있습니다.
protected 접근 제한자란?
- protected는 private과 매우 유사하게 동작합니다.
- 'protected' 키워드 뒤에 ':'(콜론)을 붙여 선언합니다.
- protected로 선언된 클래스 멤버는 클래스 외부에서 접근할 수 없습니다.
- 멤버가 선언된 클래스 내부에서는 접근이 가능합니다.
- 무엇보다 중요한 차이점은, protected 멤버를 포함하는 부모 클래스를 상속받은 파생 클래스(자식 클래스)에서도 접근할 수 있다는 것입니다.
- 따라서 protected는 주로 상속(inheritance) 개념을 활용할 때 사용됩니다.
protected 예제 코드
#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;
}실행 결과
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
위 예제에서 my_salary는 protected로 선언되어 있습니다. 파생 클래스인 derived_class의 set_salary() 함수가 부모 클래스의 protected 멤버인 my_salary에 직접 접근하여 값을 설정하는 모습을 확인할 수 있습니다. 만약 my_salary가 private이었다면 컴파일 에러가 발생했을 것입니다.
핵심 차이점 요약
| 구분 | private | protected |
|---|---|---|
| 클래스 내부 접근 | 가능 | 가능 |
| 파생 클래스 접근 | 불가능 | 가능 |
| 클래스 외부 접근 | 불가능 | 불가능 |
| 주요 용도 | 데이터 은닉 | 상속 구조에서의 데이터 공유 |
정리하면, private은 완전한 캡슐화를 통해 데이터를 보호하는 반면, protected는 상속 관계에 있는 클래스 간에는 데이터 공유를 허용하되 외부 접근만 차단하는 접근 제한자입니다. 상속을 활용한 클래스 설계 시 protected를 적절히 사용하면 코드 재사용성과 안전성을 동시에 확보할 수 있습니다.