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};
Protected implemented-in-terms-of. Rarely useful. Used in boost::compressed_pair to derive from empty classes and save memory using empty base class optimization (example below doesn't use template to keep being at the point):
Implemented-in-terms-of. The usage of the base class is only for implementing the derived class. Useful with traits and if size matters (empty traits that only contain functions will make use of the empty base class optimization). Often containment is the better solution, though. The size for strings is critical, so it's an often seen usage here
class stack {protected:vector<element> c;};
class window {protected:void registerClass(window_descriptor w);};
private member
Keep implementation details
class window {private:int width;};
Note that C-style casts purposely allows casting a derived class to a protected or private base class in a defined and safe manner and to cast into the other direction too. This should be avoided at all costs, because it can make code dependent on implementation details - but if necessary, you can make use of this technique.
class Base{public:int m_nPublic; // can be accessed by anybodyprivate: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 classm_nPrivate = 2; // not allowed: can not access private base members from derived classm_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 classcBase.m_nPrivate = 2; // not allowed: can not access private members from outside classcBase.m_nProtected = 3; // not allowed: can not access protected members from outside class}
Accessors | Base Class | Derived Class | World—————————————+————————————+———————————————+———————public | y | y | y—————————————+————————————+———————————————+———————protected | y | y | n—————————————+————————————+———————————————+———————private | | |or | y | n | nno accessor | | |
y: accessiblen: not accessible