Monday, February 21, 2011

Inheritance: Base classes & Derived Classes


Inheritance: Base classes & Derived Classes
The existing class from which another class class is derived is known as base class and the new created created is derived class.  A base class may be a direct base class of a derived class, or  an indirect base class of a derived class. A direct base class of a derived class is explicitly listed in that derived class’ header with the colon (:) notation when that derived class is declared. An indirect base class is not explicitly listed in the derived class’ header; rather the indirect base class is inherited from two or more levels up the class hierarchy.  A derived class can be defined by specifying its relationship with the base class in addition to its own details. The general forms of defining a derived class is:

class derived-classname : visibility-mode base-class-name
{
             ……. // member of derived class
};

e.g.
    class ABC           //base class
             {        ……..//members of class ABC             }


class XYZ : public ABC
         {
           ……//members of class XYZ
           }


Then, a derive class XYZ can be created as following:

class XYZ : private ABC
         {
             ……//members of class XYZ
           }








The colon indicates that the derived-class-name is derived from the base-class-name. The visibility-mode is optional and if present may be either private or public. The default visibility mode is private. Visibility mode specifies whether the features of the base class are privately derived or publicly derived. When a base class is privately inherited by a derived class, ‘public members’ of the base class become private members of derived class and therefore they are accessible only within derived class. When a base class is publicly inherited, ‘public members’ of the base class becomes ‘public members’ of the derived class. In both cases, the private members of base class are not inherited and therefore, the private members of a base class will never become the members of its derived class.

No comments:

Post a Comment