Private members of a class are not accessible to member functions of subclasses. However, sometimes we wish to make non-public members of a class accessible to a subclass; in this case, we use the protected specifier:
class Mammal { public: // ... some stuff protected: double milkProduction; }; class Dolphin : public Mammal { public: Dolphin() { milkProduction = 1.0; } };
Q: If private members of a superclass are not available to subclasses, how can we initialize the values of these members?
Answer: We need a way to call superclass constructors from a subclass constructor. For this purpose, we use the initializer list syntax, with the name of the superclass whose constructor we want to invoke:
class Point { public: Point(int x, int y) { this->x = x; this->y = y; } private: int x, y; // NOT accessible to subclasses }; class ColoredPoint : public Point { public: ColoredPoint(int x, int y, Color c) : Point(x, y) // Note initializer list syntax { color = c; } // Constructor body private: Color color; };