728x90

Class에는 Access Specifier (접근 제한자)가 존재한다. 상속에 관련된 내용을 공부하기 전에 접근 제한자와 상속관계의 접근 제한자에 대해서 포스팅한다. 

 

먼저 기본적인 클래스의 접근 제한자에 대해서 알아보면 접근 제한자는 총 3가지가 존재한다. public, protected, private이 있다. 

 

Public

public 접근 제한자에 선언된 멤버 변수 혹은 멤버 함수는 어디에서든지 접근이 가능하다.

 

Protected

protected에 선언된 멤버 함수 혹은 멤버 변수는 클래스 내부와 상속된 클래스에서 섭근이 가능하다. 

 

Private

private에 선언된 멤버 변수 혹은 멤버 함수는 오직 클래스 내부에서 접근이 가능하다. 

 

*접근 권한자를 명시해주지 않을 경우 private으로 간주한다. 

 

#include <iostream>

class Dog
{
public:
	Dog() = default;
	Dog(int age) : mAge{ age } {};
	void public_print() const
	{
		protected_print();
	}
protected:
	void protected_print() const
	{
		std::cout << "The dog is " << mAge << " years old\n";
	}
private:
	int mAge;

};

int main()
{
	Dog choco{ 9 };

	choco.public_print();
}

위 코드에서 클래스를 먼저 보게 되면 public, protected와 private 접근 제한자가 모두 사용된 것을 볼 수 있다. 먼저 private을 보면 integer형 멤버 변수 mAge가 선언되었다. 해당 멤버 변수는 클래스 내부에서만 접근이 가능하다. 다음으로 protected를 보게 되면 protercted_print() 멤버 함수가 존재한다. 이 멤버 함수에서는 private에 mAge를 불러와 출력을 하는 함수이다. protected 또한 현재 상속된 클래스가 존재하지 않기 때문에 클래스 내부에서만 접근이 가능하다. 마지막으로 public을 보면 기본 생성자와 integer 변수를 파라미터로 가지는 생성자가 있다. 그다음으로 public_print() 멤버 함수가 존재한다. 해당 멤버 함수에서 protected에 존재하는 protected_print() 멤버 함수를 호출하게 되는 멤버 함수이다. 

 

결론적으로 main함수에서 choco 객체를 생성하고 public에 있는 public_print()를 호출하고 그다음 protected에 protected_print() 함수를 호출하여 private에 있는 mAge를 불러와 출력을 하게 된다. 

 

 

Inheritance (상속)

상속에 가장 기초인 상속 접근 제한자에 대해서 간략하게 말하자면 아래 코드와 같다. 

class A 
{
    public:
       int x;
    protected:
       int y;
    private:
       int z;
};

class B : public A
{
    // x is public
    // y is protected
    // z is not accessible from B
};

class C : protected A
{
    // x is protected
    // y is protected
    // z is not accessible from C
};

class D : private A    // 'private' is default for classes
{
    // x is private
    // y is private
    // z is not accessible from D
};

위 코드는 Stack overflow의 "Difference between private, public and protected inheritance" 질문에서 발췌한 코드이다.

 

상속을 받기 위해서 어떻게 상속을 받을 것이냐를 정해주는 것이 접근 제한자이다. 각 접근 제한자에 대해서 상속받은 클래스 B, C, D에 대해서 A클래스의 멤버들의 접근 권한을 코드의 주석으로 나타냈다.

 

 

Ref.

https://stackoverflow.com/questions/860339/difference-between-private-public-and-protected-inheritance

+ Recent posts