Bruce Eckel's Thinking in C++, 2nd Ed Contents | Prev | Next

protected

Now that you’ve been introduced to inheritance, the keyword protected finally has meaning. In an ideal world, private members would always be hard-and-fast private, but in real projects there are times when you want to make something hidden from the world at large and yet allow access for members of derived classes. The protected keyword is a nod to pragmatism; it says, “This is private as far as the class user is concerned, but available to anyone who inherits from this class.”

The best approach is to leave the data members private – you should always preserve your right to change the underlying implementation. You can then allow controlled access to inheritors of your class through protected member functions:

//: C14:Protect.cpp
// The protected keyword
#include <fstream>
using namespace std;

class Base {
  int i;
protected:
  int read() const { return i; }
  void set(int ii) { i = ii; }
public:
  Base(int ii = 0) : i(ii) {}
  int value(int m) const { return m*i; }
};

class Derived : public Base {
  int j;
public:
  Derived(int jj = 0) : j(jj) {}
  void change(int x) { set(x); }
}; 

int main() {
  Derived d;
  d.change(10);
} ///:~

You will find examples of the need for protected in examples later in this book.

protected inheritance

When you’re inheriting, the base class defaults to private, which means that all the public member functions are private to the user of the new class. Normally, you’ll make the inheritance public so the interface of the base class is also the interface of the derived class. However, you can also use the protected keyword during inheritance.

Protected derivation means “implemented-in-terms-of” to other classes but “is-a” for derived classes and friends. It’s something you don’t use very often, but it’s in the language for completeness.

Contents | Prev | Next


Contact: webmaster@codeguru.com
CodeGuru - the website for developers.
[an error occurred while processing this directive]