|
|
In C++, one class can inherit the characteristics of another. The inherited class is usually called the base class. The inheriting class is referred to as a derived class. When one class inherits another, a class hierarchy is formed. The general form for inheriting a class is
class class-name : access base-class-name {
// . . .
} ;
Here, access determines how the base class is inherited, and it must be either private, public, or protected. (It can also be omitted, in which case public is assumed if the derived class is a struct, or private if the derived class is a class.) To inherit more than one class, use a comma-separated list.
If access is public, all public and protected members of the base class become public and protected members of the derived class, respectively. If access is private, all public and protected members of the base class become private members of the derived class. If access is protected, all public and protected members of the base class become protected members of the derived class.
In the following class hierarchy, derived inherits base as private. This means that i becomes a private member of derived.
class base { public: int i; }; class derived : private base { int j; public: derived(int a) { j = i = a; } int getj() { return j; } int geti() { return i; } // OK, derived has access to i }; derived ob(9); // create a derived object cout << ob.geti() << " " << ob.getj(); // OK // ob.i = 10; // ERROR, i is private to derived!
|
|