C++에서 friend(우정) 관계는 상속되지 않습니다. 즉, 부모 클래스에 friend 함수가 선언되어 있더라도, 그 클래스를 상속받은 자식 클래스에게는 해당 friend 권한이 자동으로 전달되지 않습니다.
다음 예제는 이러한 동작을 보여줍니다. display() 함수는 MyBaseClass의 friend로 선언되어 기반 클래스의 멤버에는 접근할 수 있지만, MyDerivedClass의 friend가 아니기 때문에 파생 클래스의 private 멤버에는 접근할 수 없으며, 이로 인해 컴파일 오류가 발생합니다.
예제 코드
#include <iostream>
using namespace std;
class MyBaseClass {
protected:
int x;
public:
MyBaseClass() {
x = 20;
}
friend void display();
};
class MyDerivedClass : public MyBaseClass {
private:
int y;
public:
MyDerivedClass() {
x = 40;
}
};
void display() {
MyDerivedClass derived;
cout << "The value of private member of Base class is: " << derived.x << endl;
cout << "The value of private member of Derived class is: " << derived.y << endl;
}
main() {
display();
}출력 결과
[Error] 'int MyDerivedClass::y' is private [Error] within this context
왜 오류가 발생할까?
friend 선언은 특정 클래스와 함수 사이에 맺어지는 명시적인 계약입니다. C++ 표준에서는 friend 관계가 상속 계층을 통해 전달되지 않도록 규정하고 있으므로, display()는 MyBaseClass의 protected 멤버인 x에는 접근할 수 있지만, MyDerivedClass의 private 멤버인 y에는 접근할 수 없습니다.
해결 방법
파생 클래스에서도 동일한 함수를 friend로 선언해 주면 문제를 해결할 수 있습니다.
class MyDerivedClass : public MyBaseClass {
private:
int y;
public:
MyDerivedClass() {
x = 40;
y = 50;
}
friend void display(); // 자식 클래스에도 별도의 friend 선언 필요
};이처럼 friend는 클래스 단위로 부여되는 권한이며, 상속과는 무관하게 작동한다는 점을 기억하면 설계 시 혼란을 피할 수 있습니다.