Base and Derived class
Reusability is yet another important feature of OOP. It is always nice if we could reuse something that already exits rather than trying to create the small all over again. Inheritance allows new classes to be built from older and less specialized classes instead of being rewritten from scratch.
Classes are created by first inheriting all the variables and behavior defined by some primitive class and then adding specialized variables and behaviors. The mechanism of deriving a new class from an old one is called inheritance. The old class is referred to as the base class and the new one is called the derived class.
Defining Derived Class
A derived class is defined by specifying its relationship with the base class in addition to its own details. The general form of defining a derived class is.
Class derived-classname : visibility-mode base -classname
{
members of derived class
}
When a base class is privately inherited by derived class, ‘public members’ of the base class become ’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 derived class. They are inaccessible to the objects of the derived class. Remember a public member of a class can be accessed by its own objects using the dot operator. The result is that no member of the base class is accessible to the objects of the derived class.
When a base class is publicly inherited by derived class, ‘public members’ of the base class become ‘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.
No comments:
Post a Comment