FAQ 17.04 Why can t a derived class access the private: members of its base class?

FAQ 17.04 Why can't a derived class access the private: members of its base class?

A derived class can't access the private: members of its base class because the base class intentionally hides some of its implementation details from its derived classes.

Suppose class Fred contains a member datum or member function that is likely to change. Unless derived classes need to access this member, the base class Fred would be wise to declare the member as private:. This reduces the ripple effect of changes in the base class. For example, the private: member can be removed or modified without fear of breaking derived classes. That is, the derived classes are protected from rewrites whenever the semantics or even existence of the private: member change.

For example, class Wilma below can access publ_ and prot_, but cannot access priv_.

 #include <iostream> using namespace std; class Fred { public:   Fred() throw();   int publ_; protected:   int prot_; private:   int priv_; }; Fred::Fred() throw() : publ_(1) , prot_(2) , priv_(3) { } class Wilma : public Fred { public:   void printem() const throw(); }; void Wilma::printem() const throw() {   cout << publ_ << '\n';                             <-- 1   cout << prot_ << '\n';                             <-- 2   #ifdef GENERATE_ERROR     cout << priv_ << '\n';                           <-- 3   #endif } int main() {   Wilma a;   a.printem(); } 

(1) OK: Derived can access base's public: stuff

(2) OK: Derived can access base's protected: stuff

(3) Error: Derived cannot access base's private: stuff

The designer of a base class gives derived classes access to implementation details by declaring them as protected:.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net