Defining of Derived Classes in C++

How do we define a derived class in C++

A derived class is defined by specifying it relationship with the base class in addition to its own details.

The general form of defining a derived class is:

class derived-class-name : visibility-mode base-class-name
     {
          ...
          ...     //members of derived class
          ...
     };

where,
class is the required keyword,
derived-class-name is the name given to the derived class,
base-class-name is the name given to the base class,
: (colon) indicates that the derived-class-name is derived from the base-class-name,
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.

Examples:

class ABC : private XYZ     //private derivation
     {
          members of ABC
     };

class ABC : public XYZ     //public derivation
     {
          members of ABC
     };

class ABC : XYZ     //private derivation by default
     {
          members of ABC
     };

When a base class is privately inherited by a derived class, ‘public members’ of the base class becomes private members of the derived class and therefore the public members of the base class can only be accessed by the member functions of the of the derived class. They are inaccessible to the objects of the derived class.

Remember, a public member of the class can be accessed by its own objects by using the dot operator. The result is that no member of the base class is accessible to the objects of the derived class in case of private derivation.

On the other hand, when the base class is publicly inherited, ‘public members’ of the base class becomes ‘public members’ of the derived class and therefore they are accessible to the objects of the derived class.

In both the cases, the private members are not inherited and therefore, the private members of a base class will never become the members of its derived class.

In inheritance, some of the base class data elements and member functions are inherited into the derived clas. We can also add our own data and member functions and thus extend the functionality of the base class. Inheritance, when used to modify and extend the capabilities of the existing classes, becomes a very powerful tool for incremental program development.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: