ACCESS CONTROL UNDER INHERITANCE

The access to inherited members in a derived class needs to be looked at more closely. Consider the status of the private members of a base class in a derived class.

There was a good reason to choose the version of the class CBox with public data members in the previous example, rather than the later, more secure version with private data members. Although private data members of a base class are also members of a derived class, they remain private to the base class in the derived class, so member functions defined in the derived class cannot access them. They are only accessible in the derived class through function members of the base class that are not private. You can demonstrate this very easily by changing all the CBox class data members to private and putting a Volume() function in the derived class CCandyBox, so that the class definition is as follows:

// Version of the classes that will not compile #include <cstring> // For strlen() and strcpy() class CBox { public: explicit CBox(double lv = 1.0, double wv = 1.0, double hv = 1.0): m_Length(lv), m_Width(wv), m_Height(hv){} private: double m_Length; double m_Width; double m_Height; }; class CCandyBox: public CBox { public: char* m_Contents; // Function to calculate the volume of a CCandyBox object double Volume() const // Error - members not accessible { return m_Length*m_Width*m_Height; } explicit CCandyBox(const char* str = "Candy") // Constructor { m_Contents = new char[ strlen(str) + ...

Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.