gotchacppCritical
What is the difference between public, private, and protected inheritance?
Viewed 0 times
privateandprotectedbetweenpublicthedifferenceinheritancewhat
Problem
What is the difference between
public, private, and protected inheritance in C++?Solution
To answer that question, I'd like to describe member's accessors first in my own words. If you already know this, skip to the heading "next:".
There are three accessors that I'm aware of:
Let:
By "is aware of", I mean "acknowledge the existence of, and thus be able to access".
next:
The same happens with public, private and protected inheritance. Let's consider a class
There are three accessors that I'm aware of:
public, protected and private. Let:
class Base {
public:
int publicMember;
protected:
int protectedMember;
private:
int privateMember;
};- Everything that is aware of
Baseis also aware thatBasecontainspublicMember.
- Only the children (and their children) are aware that
BasecontainsprotectedMember.
- No one but
Baseis aware ofprivateMember.
By "is aware of", I mean "acknowledge the existence of, and thus be able to access".
next:
The same happens with public, private and protected inheritance. Let's consider a class
Base and a class Child that inherits from Base.- If the inheritance is
public, everything that is aware ofBaseandChildis also aware thatChildinherits fromBase.
- If the inheritance is
protected, onlyChild, and its children, are aware that they inherit fromBase.
- If the inheritance is
private, no one other thanChildis aware of the inheritance.
Code Snippets
class Base {
public:
int publicMember;
protected:
int protectedMember;
private:
int privateMember;
};Context
Stack Overflow Q#860339, score: 1210
Revisions (0)
No revisions yet.