class base {
   int i, j;
   void set(int a, int b) { i=a; j=b; }
   void show() { cout << i << " " << j << "\n"; }
class derived : public base {
   int k;
   derived(int x) { k=x; }
   void showk() { cout << k << "\n"; }

In the declaration above why is it necessary to declare base as public(or private) within the definition of class derived?

the default inheritance is private inheritance if you not explicitly mentioned.

well private inheritance is more likely an has-a relationship than the is-a relationship. and the bottom line is use private inheritance where you can't avoid and use composition where every elsewhere.

there are three object oriented concepts relate to this,
source : http://weblogs.foxite.com/andykramek/archive/2007/01/07/3096.aspx
· Decorator Modify behavior, without modifying an existing interface

· Adapter Modify interface without modifying behavior

· Wrapper Provide interface for, and services to, behavior that is defined elsewhere
and the C++ language bottom line is always use private inheritance
that you can't avoid it. ( source from C++ FAQ ).

I believe private inheritance more accurately represents "implemented in terms of"; which is slightly different to 'has a'; the main difference being that a privately inherited implementation is guaranteed to be initialised before a class' own private members. Something which is associated with a few interesting initialisation tricks.

This article has been dead for over six months. Start a new discussion instead.