데이터 베이스 MySQL 튜토리얼 Public Private Protect Inheritance and access specifiers

Public Private Protect Inheritance and access specifiers

Jun 07, 2016 pm 03:50 PM
private public

In the previous lessons on inheritance, we’ve been making all of our data members public in order to simplify the examples. In this div, we’ll talk about the role of access specifiers in the inheritance process, as well as cover the diff

In the previous lessons on inheritance, we’ve been making all of our data members public in order to simplify the examples. In this div, we’ll talk about the role of access specifiers in the inheritance process, as well as cover the different types of inheritance possible in C++.

To this point, you’ve seen the private and public access specifiers, which determine who can access the members of a class. As a quick refresher, public members can be accessed by anybody. Private members can only be accessed by member functions of the same class. Note that this means derived classes can not access private members!

1

2

3

4

5

6

7

class Base

{

private:

    int m_nPrivate; // can only be accessed by Base member functions (not derived classes)

public:

    int m_nPublic; // can be accessed by anybody

};

When dealing with inherited classes, things get a bit more complex.

First, there is a third access specifier that we have yet to talk about because it’s only useful in an inheritance context. The protected access specifier restricts access to member functions of the same class, or those of derived classes.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

class Base

{

public:

    int m_nPublic; // can be accessed by anybody

private:

    int m_nPrivate; // can only be accessed by Base member functions (but not derived classes)

protected:

    int m_nProtected; // can be accessed by Base member functions, or derived classes.

};

 

class Derived: public Base

{

public:

    Derived()

    {

        // Derived's access to Base members is not influenced by the type of inheritance used,

        // so the following is always true:

 

        m_nPublic = 1; // allowed: can access public base members from derived class

        m_nPrivate = 2; // not allowed: can not access private base members from derived class

        m_nProtected = 3; // allowed: can access protected base members from derived class

    }

};

 

int main()

{

    Base cBase;

    cBase.m_nPublic = 1; // allowed: can access public members from outside class

    cBase.m_nPrivate = 2; // not allowed: can not access private members from outside class

    cBase.m_nProtected = 3; // not allowed: can not access protected members from outside class

}

Second, when a derived class inherits from a base class, the access specifiers may change depending on the method of inheritance. There are three different ways for classes to inherit from other classes: public, private, and protected.

To do so, simply specify which type of access you want when choosing the class to inherit from:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

// Inherit from Base publicly

class Pub: public Base

{

};

 

// Inherit from Base privately

class Pri: private Base

{

};

 

// Inherit from Base protectedly

class Pro: protected Base

{

};

 

class Def: Base // Defaults to private inheritance

{

};

If you do not choose an inheritance type, C++ defaults to private inheritance (just like members default to private access if you do not specify otherwise).

That gives us 9 combinations: 3 member access specifiers (public, private, and protected), and 3 inheritance types (public, private, and protected).

The rest of this div will be devoted to explaining the difference between these.

Before we get started, the following should be kept in mind as we step through the examples. There are three ways that members can be accessed:

  • A class can always access it’s own members regardless of access specifier.
  • The public accesses the members of a class based on the access specifiers of that class.
  • A derived class accesses inherited members based on the access specifiers of its immediate parent. A derived class can always access it’s own members regardless of access specifier.

This may be a little confusing at first, but hopefully will become clearer as we step through the examples.

Public inheritance

Public inheritance is by far the most commonly used type of inheritance. In fact, very rarely will you use the other types of inheritance, so your primary focus should be on understanding this div. Fortunately, public inheritance is also the easiest to understand. When you inherit a base class publicly, all members keep their original access specifications. Private members stay private, protected members stay protected, and public members stay public.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

class Base

{

public:

    int m_nPublic;

private:

    int m_nPrivate;

protected:

    int m_nProtected;

};

 

class Pub: public Base

{

    // Public inheritance means:

    // m_nPublic stays public

    // m_nPrivate stays private

    // m_nProtected stays protected

 

    Pub()

    {

        // The derived class always uses the immediate parent's class access specifications

        // Thus, Pub uses Base's access specifiers

        m_nPublic = 1; // okay: anybody can access public members

        m_nPrivate = 2; // not okay: derived classes can't access private members in the base class!

        m_nProtected = 3; // okay: derived classes can access protected members

    }

};

 

int main()

{

    // Outside access uses the access specifiers of the class being accessed.

    // In this case, the access specifiers of cPub.  Because Pub has inherited publicly from Base,

    // no access specifiers have been changed.

    Pub cPub;

    cPub.m_nPublic = 1; // okay: anybody can access public members

    cPub.m_nPrivate = 2; // not okay: can not access private members from outside class

    cPub.m_nProtected = 3; // not okay: can not access protected members from outside class

}

This is fairly straightforward. The things worth noting are:

  1. Derived classes can not directly access private members of the base class.
  2. The protected access specifier allows derived classes to directly access members of the base class while not exposing those members to the public.
  3. The derived class uses access specifiers from the base class.
  4. The outside uses access specifiers from the derived class.

To summarize in table form:

Public inheritance
Base access specifier Derived access specifier Derived class access? Public access?
Public Public Yes Yes
Private Private No No
Protected Protected Yes No

Private inheritance

With private inheritance, all members from the base class are inherited as private. This means private members stay private, and protected and public members become private.

Note that this does not affect that way that the derived class accesses members inherited from its parent! It only affects the code trying to access those members through the derived class.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

class Base

{

public:

    int m_nPublic;

private:

    int m_nPrivate;

protected:

    int m_nProtected;

};

 

class Pri: private Base

{

    // Private inheritance means:

    // m_nPublic becomes private

    // m_nPrivate stays private

    // m_nProtected becomes private

 

    Pri()

    {

        // The derived class always uses the immediate parent's class access specifications

        // Thus, Pub uses Base's access specifiers

        m_nPublic = 1; // okay: anybody can access public members

        m_nPrivate = 2; // not okay: derived classes can't access private members in the base class!

        m_nProtected = 3; // okay: derived classes can access protected members

    }

};

 

int main()

{

    // Outside access uses the access specifiers of the class being accessed.

    // Note that because Pri has inherited privately from Base,

    // all members of Base have become private when access through Pri.

    Pri cPri;

    cPri.m_nPublic = 1; // not okay: m_nPublic is now a private member when accessed through Pri

    cPri.m_nPrivate = 2; // not okay: can not access private members from outside class

    cPri.m_nProtected = 3; // not okay: m_nProtected is now a private member when accessed through Pri

 

    // However, we can still access Base members as normal through Base:

    Base cBase;

    cBase.m_nPublic = 1; // okay, m_nPublic is public

    cBase.m_nPrivate = 2; // not okay, m_nPrivate is private

    cBase.m_nProtected = 3; // not okay, m_nProtected is protected

}

To summarize in table form:

Private inheritance
Base access specifier Derived access specifier Derived class access? Public access?
Public Private Yes No
Private Private No No
Protected Private Yes No

Protected inheritance

Protected inheritance is the last method of inheritance. It is almost never used, except in very particular cases. With protected inheritance, the public and protected members become protected, and private members stay private.

To summarize in table form:

Protected inheritance
Base access specifier Derived access specifier Derived class access? Public access?
Public Protected Yes No
Private Private No No
Protected Protected Yes No

Protected inheritance is similar to private inheritance. However, classes derived from the derived class still have access to the public and protected members directly. The public (stuff outside the class) does not.

Summary

The way that the access specifiers, inheritance types, and derived classes interact causes a lot of confusion. To try and clarify things as much as possible:

First, the base class sets it’s access specifiers. The base class can always access it’s own members. The access specifiers only affect whether outsiders and derived classes can access those members.

Second, derived classes have access to base class members based on the access specifiers of the immediate parent. The way a derived class accesses inherited members is not affected by the inheritance method used!

Finally, derived classes can change the access type of inherited members based on the inheritance method used. This does not affect the derived classes own members, which have their own access specifiers. It only affects whether outsiders and classes derived from the derived class can access those inherited members.

A final example:

1

2

3

4

5

6

7

8

9

class Base

{

public:

    int m_nPublic;

private:

    int m_nPrivate;

protected:

    int m_nProtected;

};

Base can access it’s own members without restriction. The public can only access m_nPublic. Derived classes can access m_nPublic and m_nProtected.

1

2

3

4

5

6

7

8

9

class D2: private Base

{

public:

    int m_nPublic2;

private:

    int m_nPrivate2;

protected:

    int m_nProtected2;

}

D2 can access it’s own members without restriction. D2 can access Base’s members based on Base’s access specifiers. Thus, it can access m_nPublic and m_nProtected, but not m_nPrivate. Because D2 inherited Base privately, m_nPublic, m_nPrivate, and m_nProtected are now private when accessed through D2. This means the public can not access any of these variables when using a D2 object, nor can any classes derived from D2.

1

2

3

4

5

6

7

8

9

class D3: public D2

{

public:

    int m_nPublic3;

private:

    int m_nPrivate3;

protected:

    int m_nProtected3;

};

D3 can access it’s own members without restriction. D3 can access D2′s members based on D2′s access specifiers. Thus, D3 has access to m_nPublic2 and m_nProtected2, but not m_nPrivate2. D3 access to Base members is controlled by the access specifier of it’s immediate parent. This means D3 does not have access to any of Base’s members because they all became private when D2 inherited them.

http://www.learncpp.com/cpp-tutorial/115-inheritance-and-access-specifiers/

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Alter Table 문을 사용하여 MySQL에서 테이블을 어떻게 변경합니까? Alter Table 문을 사용하여 MySQL에서 테이블을 어떻게 변경합니까? Mar 19, 2025 pm 03:51 PM

이 기사는 MySQL의 Alter Table 문을 사용하여 열 추가/드롭 테이블/열 변경 및 열 데이터 유형 변경을 포함하여 테이블을 수정하는 것에 대해 설명합니다.

MySQL 연결에 대한 SSL/TLS 암호화를 어떻게 구성합니까? MySQL 연결에 대한 SSL/TLS 암호화를 어떻게 구성합니까? Mar 18, 2025 pm 12:01 PM

기사는 인증서 생성 및 확인을 포함하여 MySQL에 대한 SSL/TLS 암호화 구성에 대해 설명합니다. 주요 문제는 자체 서명 인증서의 보안 영향을 사용하는 것입니다. [문자 수 : 159]

MySQL에서 큰 데이터 세트를 어떻게 처리합니까? MySQL에서 큰 데이터 세트를 어떻게 처리합니까? Mar 21, 2025 pm 12:15 PM

기사는 MySQL에서 파티셔닝, 샤딩, 인덱싱 및 쿼리 최적화를 포함하여 대규모 데이터 세트를 처리하기위한 전략에 대해 설명합니다.

인기있는 MySQL GUI 도구는 무엇입니까 (예 : MySQL Workbench, Phpmyadmin)? 인기있는 MySQL GUI 도구는 무엇입니까 (예 : MySQL Workbench, Phpmyadmin)? Mar 21, 2025 pm 06:28 PM

기사는 MySQL Workbench 및 Phpmyadmin과 같은 인기있는 MySQL GUI 도구에 대해 논의하여 초보자 및 고급 사용자를위한 기능과 적합성을 비교합니다. [159 자].

드롭 테이블 문을 사용하여 MySQL에서 테이블을 어떻게 드롭합니까? 드롭 테이블 문을 사용하여 MySQL에서 테이블을 어떻게 드롭합니까? Mar 19, 2025 pm 03:52 PM

이 기사에서는 Drop Table 문을 사용하여 MySQL에서 테이블을 떨어 뜨리는 것에 대해 설명하여 예방 조치와 위험을 강조합니다. 백업 없이는 행동이 돌이킬 수 없으며 복구 방법 및 잠재적 생산 환경 위험을 상세하게합니다.

JSON 열에서 인덱스를 어떻게 생성합니까? JSON 열에서 인덱스를 어떻게 생성합니까? Mar 21, 2025 pm 12:13 PM

이 기사에서는 PostgreSQL, MySQL 및 MongoDB와 같은 다양한 데이터베이스에서 JSON 열에서 인덱스를 작성하여 쿼리 성능을 향상시킵니다. 특정 JSON 경로를 인덱싱하는 구문 및 이점을 설명하고 지원되는 데이터베이스 시스템을 나열합니다.

외국 키를 사용하여 관계를 어떻게 표현합니까? 외국 키를 사용하여 관계를 어떻게 표현합니까? Mar 19, 2025 pm 03:48 PM

기사는 외국 열쇠를 사용하여 데이터베이스의 관계를 나타내고 모범 사례, 데이터 무결성 및 피할 수있는 일반적인 함정에 중점을 둡니다.

일반적인 취약점 (SQL 주입, 무차별 적 공격)에 대해 MySQL을 어떻게 보호합니까? 일반적인 취약점 (SQL 주입, 무차별 적 공격)에 대해 MySQL을 어떻게 보호합니까? Mar 18, 2025 pm 12:00 PM

기사는 준비된 명령문, 입력 검증 및 강력한 암호 정책을 사용하여 SQL 주입 및 무차별 적 공격에 대한 MySQL 보안에 대해 논의합니다 (159 자)

See all articles