Search

Enter your search terms

Submit search form

11.5 — Inheritance and access specifiers

By Alex on January 14th, 2008 | last modified by Alex on January 6th, 2017

In the previous lessons in this chapter, you’ve learned a bit about how base inheritance works. In all of our examples so far, we’ve used public inheritance. That is, our derived class publicly inherits the base class.

In this lesson, we’ll take a closer look at public inheritance, as well as the two other kinds of inheritance (private and protected). We’ll also explore how the different kinds of inheritance interact with access specifiers to allow or restrict access to members.

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 or friends. This means derived classes can not access private members of the base class directly!

1

2

3

4

5

6

7

classBase

{

private:

intm_private;// can only be accessed by Base members and friends (not derived classes)

public:

intm_public;// can be accessed by anybody

};

This is pretty straightforward, and you should be quite used to it by now.

The protected access specifier

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

C++ has a third access specifier that we have yet to talk about because it’s only useful in an inheritance context. The protected access specifier allows the class the member belongs to, friends, and derived classes to access the member. However, protected members are not accessible from outside the 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

classBase

{

public:

intm_public;// can be accessed by anybody

private:

intm_private;// can only be accessed by Base members and friends (but not derived classes)

protected:

intm_protected;// can be accessed by Base members, friends, and derived classes

};

classDerived:publicBase

{

public:

Derived()

{

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

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

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

}

};

intmain()

{

Base base;

base.m_public=1;// allowed: can access public members from outside class

base.m_private=2;// not allowed: can not access private members from outside class

base.m_protected=3;// not allowed: can not access protected members from outside class

}

In the above example, you can see that the protected base member m_protected is directly accessible by the derived class, but not by the public.

So when should I use the protected access specifier?

With a protected attribute in a base class, derived classes can access that member directly. This means that if you change anything about that protected attribute (the type, what the value means, etc…), you’ll probably need to change both the base class AND all of the derived classes.

Therefore, using the protected access specifier is most useful when you (or your team) are going to be the ones deriving from your own classes, and the number of derived classes is reasonable. That way, if you make a change to the implementation of the base class, and updates to the derived classes are necessary as a result, you can make the updates yourself (and have it not take forever, since the number of derived classes is limited).

Making your members private gives you better encapsulation and insulates derived classes from changes to the base class. But there’s also a cost to build a public or protected interface to support all the access methods or capabilities that the public and/or derived classes need. That’s additional work that’s probably not worth it, unless you expect someone else to be the one deriving from your class, or you have a huge number of derived classes, where the cost of updating them all would be expensive.

Different kinds of inheritance, and their impact on access

First, 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

classPub:publicBase

{

};

// Inherit from Base privately

classPri:privateBase

{

};

// Inherit from Base protectedly

classPro:protectedBase

{

};

classDef: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).

So what’s the difference between these? In a nutshell, when members are inherited, the access specifier for an inherited member may be changed (in the derived class only) depending on the type of inheritance used. Put another way, members that were public or protected in the base class may change access specifiers in the derived class.

This might seem a little confusing, but it’s not that bad. We’ll spend the rest of this lesson exploring this in detail.

Keep in mind the following rules as we step through the examples:

A class can always access its own (non-inherited) members.

The public accesses the members of a class based on the access specifiers of the class it is accessing.

A class accesses inherited members based on the access specifier inherited from the parent class. This varies depending on the access specifier and type of inheritance used.

Public inheritance

Public inheritance is by far the most commonly used type of inheritance. In fact, very rarely will you see or use the other types of inheritance, so your primary focus should be on understanding this section. Fortunately, public inheritance is also the easiest to understand. When you inherit a base class publicly, inherited public members stay public, and inherited protected members stay protected. Inherited private members, which were inaccessible because they were private in the base class, stay inaccessible.

Access specifier in base class

Access specifier when inherited publicly

Public

Public

Private

Inaccessible

Protected

Protected

Here’s an example showing how things work:

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

classBase

{

public:

intm_public;

private:

intm_private;

protected:

intm_protected;

};

classPub:publicBase// note: public inheritance

{

// Public inheritance means:

// Public inherited members stay public (so m_public is treated as public)

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

Base base;

base.m_public=1;// okay: m_public is public in Base

base.m_private=2;// not okay: m_private is private in Base

base.m_protected=3;// not okay: m_protected is protected in Base

Pub pub;

pub.m_public=1;// okay: m_public is public in Pub

pub.m_private=2;// not okay: m_private is inaccessible in Pub

pub.m_protected=3;// not okay: m_protected is protected in Pub

This is the same as the example above where we introduced the protected access specifier, except that we’ve instantiated the derived class as well, just to show that with public inheritance, things work identically in the base and derived class.

Public inheritance is what you should be using unless you have a specific reason not to.

Rule: Use public inheritance unless you have a specific reason to do otherwise.

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 the 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

classBase

{

public:

intm_public;

private:

intm_private;

protected:

intm_protected;

};

classPri:privateBase// note: private inheritance

{

// Private inheritance means:

// Public inherited members become private (so m_public is treated as private)

// Protected inherited members become private (so m_protected is treated as private)

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

m_protected=3;// okay: m_protected is now private in Pri

}

};

intmain()

{

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

// In this case, the access specifiers of base.

Base base;

base.m_public=1;// okay: m_public is public in Base

base.m_private=2;// not okay: m_private is private in Base

base.m_protected=3;// not okay: m_protected is protected in Base

Pri pri;

pri.m_public=1;// not okay: m_public is now private in Pri

pri.m_private=2;// not okay: m_private is inaccessible in Pri

pri.m_protected=3;// not okay: m_protected is now private in Pri

To summarize in table form:

Access specifier in base class

Access specifier when inherited privately

Public

Private

Private

Inaccessible

Protected

Private

Private inheritance can be useful when the derived class has no obvious relationship to the base class, but uses the base class for implementation internally. In such a case, we probably don’t want the public interface of the base class to be exposed through objects of the derived class (as it would be if we inherited publicly). Private inheritance also ensures the derived class must use the public interface of the base class, ensuring encapsulation is upheld.

But in reality, this is rarely used.

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 inaccessible.

Because this form of inheritance is so rare, we’ll skip the example and just summarize with a table:

Access specifier in base class

Access specifier when inherited protectedly

Public

Protected

Private

Inaccessible

Protected

Protected

A final example

1

2

3

4

5

6

7

8

9

classBase

{

public:

intm_public;

private:

intm_private;

protected:

intm_protected;

};

Base can access its own members without restriction. The public can only access m_public. Derived classes can access m_public and m_protected.

1

2

3

4

5

6

7

8

9

10

11

12

13

classD2:privateBase// note: private inheritance

{

// Private inheritance means:

// Public inherited members become private

// Protected inherited members become private

// Private inherited members stay inaccessible

public:

intm_public2;

private:

intm_private2;

protected:

intm_protected2;

};

D2 can access its own members without restriction. D2 can access Base’s m_public and m_protected members, but not m_private. Because D2 inherited Base privately, m_public and m_protected are now considered private when accessed through D2. This means the public can not access these variables when using a D2 object, nor can any classes derived from D2.

1

2

3

4

5

6

7

8

9

10

11

12

13

classD3:publicD2

{

// Public inheritance means:

// Public inherited members stay public

// Protected inherited members stay protected

// Private inherited members stay inaccessible

public:

intm_public3;

private:

intm_private3;

protected:

intm_protected3;

};

D3 can access its own members without restriction. D3 can access D2’s m_public2 and m_protected2 members, but not m_private2. Because D3 inherited D2 publicly, m_public2 and m_protected2 keep their access specifiers when accessed through D3. D3 has no access to Base’s m_private, which was already private in Base. Nor does it have access to Base’s m_protected or m_public, both of which became private when D2 inherited them.

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, a class (and friends) can always access its own non-inherited members. The access specifiers only affect whether outsiders and derived classes can access those members.

Second, when derived classes inherit members, those members may change access specifiers in the derived class. This does not affect the derived classes’ own (non-inherited) members (which have their own access specifiers). It only affects whether outsiders and classes derived from the derived class can access those inherited members.

Here’s a table of all of the access specifier and inheritance types combinations:

Access specifier in base class

Access specifier when inherited publicly

Access specifier when inherited privately

Access specifier when inherited protectedly

Public

Public

Private

Protected

Private

Inaccessible

Inaccessible

Inaccessible

Protected

Protected

Private

Protected

As a final note, although in the examples above, we’ve only shown examples using member variables, these access rules hold true for all members (e.g. member functions and types declared inside the class).

I ran one small program(mentioned below) to understand Public access specifier .Could not understand how derived class can access private variable(x) of base class through public api(print()) of base class.Compilation error comes if try to access private variable directly from derived class but its accessible through another derived api print().
As you mentioned in tutorial, private members are inaccessible to derived class even inherited publicly.
And Derived object has its own independant memory space where both base portion(inherited) and derived portion resides.
then how private variable which was inaccesible came to derived object memory space.Kindly clarify.

Not sure I understand the question. A derived class has a base portion and a derived portion, right? All of the members defined in the base class stay in the base portion, and all of the members defined in the derived class stay in the derived portion. A public base member is accessible from the derived portion of the class (even though it's in the base portion), because it is public. A private base member is also in the base portion, but is not accessible from the derived portion because the access specifier forbids it.

Thank you for the clarification that indeed is detailed in this lesson.
As I see it, if we regard all the members of the base class as being owned by the child class, we are actually possibly creating a new access type of members in the child class.
These are the inaccessibles.
They are not private to the child class, bcz if they were they were accessible from within it (they were indeed private in the parent class).
So a class can have possibly members that are one of the ***four*** following access types:
a. inaccessible
b. private
c. protected
d. public
Did I get it right this time?
If yes, the inaccessible seems to be a new "membership access type concept" I overlooked until now.
Thank you again.

Right. I prefer the more accurate viewpoint that members of the base class as still owned by the base class, and understand that the child is simply a third type of "viewer" (the other two being the public, and the base class itself). From that viewpoint, members of the base class are owned by the base class, and private members are inaccessible to both the public and derived classes, as they are private to the base class that owns them.

Regarding:
"That is, our derived class publicly inherits the base class..."
does this mean:
"That is, our derived class publicly inherits the base class meaning it inherits only public members of the base class..."
If correct, should this not be stated explicitly?

The derived class inherits all of the members, even the private ones, and those members keep their same access levels. This means the private members of the base class are inaccessible to the derived class, even though they are still inherited.

Hello, Alex.
In the following short program I name a variable in Derived class with the same name as the one in the Base class, and the function inside Derived class favors its own class 's variable. How can I access the Base 's variable inside the Derived class without using some public function in Base?

I'm not familiar enough with other C-style languages to authoritatively say. But best guess is a lot, though they may only support a subset of the functionality that's available in C++, or do things in a slightly different way (using a different syntax or keyword).

there are confusion in my head about 2 things.
1. can you explain more "So when should I use the protected access specifier?" Section, i don't get it. or give example about it. at paragraph one i confuse, what implementetion? what updates are necessary? what and why it is not take forever? and at paragraph two, what additional work? what update?

2. the last sentence of "Private inheritance" section "the derived class has no visible relationship to the base class" what is visible relationship mean?

1) Sure. With a protected attribute in a base class, derived classes can access that member directly. This means that if you change anything about that protected attribute (the type, what the value means, etc...), you'll probably need to change both the base class AND all of the derived classes.

2) A square derived class obviously has a visible (obvious) relationship with a shape base class, since they're conceptually related. If square is publicly inherited from shape, the interface (public functions) of square becomes part of the interface of shape, and both are accessible externally. Now consider a Homework class that holds students names and grades in a map. That Homework class might be implemented using a Map class, but that's just an internal detail. In this case, we probably don't want the interface of the Map class to be accessible through Homework. Inheriting privately accomplishes both this, and ensuring that Homework can only access Map through its public interface, ensuring we don't violate encapsulation (assuming that's important in this context).

I've made a few tweaks to the lesson text to try and make these points clearer. Thanks for the feedback.

"As a final note, although in the examples above, we've only shown examples using member variables, these access rules hold true for all members (e.g. member functions and types declared inside the class)."

The tables really clear things out!!
However, I think there's one more caveat about the inheritance type. Instead of just a easier way of restrict the member access of the class all at once, I think it also influence how public/derived class view the fact of inheritance.

Eg:

1

2

3

4

5

6

7

8

9

10

11

12

13

classBase

{

};

classDerived:protectedBase

{

};

intmain()

{

Derivedd;

Base*pD=&d;// error: 'Base' is an inaccessible base of 'Derived'

}

This doesn't work because the fact that Derived is derived form Base is hidden from the public (since the inheritance is protected).

This lesson was really interesting. Thanks for the good work. There was a typo in this sentence: (Private inheritance, paragraph 2), Note that this does not affect "that" way that the derived class accesses members inherited from its parent! "That" should be "the". Can you give me typical cases where private inheritance would be useful? Thanks.