More C++ Idioms/Friendship and the Attorney-Client

진영민·2022년 7월 9일
1

More C++ Idioms

목록 보기
3/10

1. 문제 상황

c++에서 friend는 외부의 함수에게 내부 private까지도 접근할 수 있는 권한을 준다.
encapsulation을 침해하기도 한다.

1-1 예시 코드

class temp1 {
private:
	int a = 0;
	int b = 1;
	int c = 2;
friend class temp2;
};

class temp2 {
public:
int geta(temp1 temp) {
	return temp.a;
}
};

int main(void) {
	temp1 temp;
	temp2 getFunc;
	int result = getFunc.geta(temp);
	std::cout <<result<< std::endl;
}

이러한 방법으로 temp1안에 있는 private를 꺼낼 수 있다.

따라서 괜히 private로 보호한 정보를 노출 시킬 위험이 있어 잘 사용하지 않는 방식이다.

friend는 클래스 전체가 아닌 함수 하나만에게도 적용할 수 있다.

결론 : 객체지향개념에서는 깽판 그 자체이며, 사용하지 말자!

profile
코린이

0개의 댓글