반응형
상속과 접근 지정자
상속 적용 시 부모 클래스 앞에
public,protected,private와 같은 접근 지정자를 붙인다.- 자식 클래스에서 기본적으로 부모 클래스의 멤버들을 어떤 권한으로 받아들일지에 관한 것이다.
예제
아래 예제의 경우
public으로 상속받았으므로 멤버들의 기본 접근 권한이public이 된다.protected,private은public보다 보안이 더 강하므로 그대로 적용된다.
#include <iostream> class Base { public: int public_; protected: int protected_; private: int private_; }; class Derived : public Base { }; int main() { using namespace std; Derived d; d.public_ = 1024; }public대신protected를 사용하는 예제public멤버가Derived클래스에서는protected로 적용된다.Derived클래스 내부에서는public_,protected_모두 접근할 수 있다.
#include <iostream> class Base { public: int public_; protected: int protected_; private: int private_; }; class Derived : protected Base { }; int main() { using namespace std; Derived d; d.public_ = 1024; // 에러 }다음과 같이 접근 오류가 발생한다.
error C2247: 'Base::public_' not accessible because 'Derived' uses 'protected' to inherit from 'Base'
Base클래스의 멤버가Derived클래스 안으로 다음과 같이 들어온 것처럼 생각하면 된다.class Derived : protected Base { protected: int Base::public_; int Base::protected_; };
2번 상속하는 경우
Base->Derived->GrandChild로 상속이 적용되는 예제Derived클래스가Base클래스를protected로 받은 경우GrandChild클래스에서Base클래스의protected멤버까지 접근할 수 있다.
#include <iostream> class Base { public: int public_; protected: int protected_; private: int private_; }; class Derived : protected Base { public: Derived() { Base::public_; Base::protected_; } }; class GrandChild : public Derived { public: GrandChild() { Derived::Base::public_; Derived::Base::protected_; } }; int main() { using namespace std; Derived d; }Derived클래스가Base클래스를private로 받은 경우#include <iostream> class Base { public: int public_; protected: int protected_; private: int private_; }; class Derived : private Base { public: Derived() { Base::public_; Base::protected_; } }; class GrandChild : public Derived { public: GrandChild() { Derived::Base::public_; // 에러 Derived::Base::protected_; // 에러 } }; int main() { using namespace std; Derived d; }Derived클래스에서는Base클래스의 멤버가private상태이기 때문에 접근할 수 있다.하지만
GrandChild클래스에서는Derived클래스의private멤버에 접근할 수 없으므로 다음과 같은 에러가 발생한다.error C2247: 'Base::public_' not accessible because 'Derived' uses 'private' to inherit from 'Base'
반응형
'SW개발 > C++' 카테고리의 다른 글
| C++ 상속받은 멤버의 접근 권한 변경 (0) | 2021.03.20 |
|---|---|
| C++ 함수 오버라이딩 (0) | 2021.03.20 |
| C++ 상속과 패딩 (0) | 2021.03.20 |
| C++ 유도된 클래스들의 소멸 순서 (0) | 2021.03.19 |
| C++ 유도된 클래스들의 생성 순서 (0) | 2021.03.19 |