Hi,

class base {
   int i, j;
public:
   void set(int a, int b) { i=a; j=b; }
   void show() { cout << i << " " << j << "\n"; }
};
class derived : public base {
   int k;
public:
   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
quote--
· 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
quote--
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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.