8.4 Inheritance - shahzade baujiti

Breaking

Wednesday, April 24, 2019

8.4 Inheritance


8.4 Inheritance

Inheritance is one of the key feature of object-oriented programming including C++ which allows user to create a new class(derived class) from a existing class(base class). The derived class inherits all feature from a base class and it can have additional features of its own.

Inheritance makes the code reusable. When we inherit an existing class, all its methods and fields become available in the new class, hence code is reused.
Note that All members of a class except Private, are inherited.

Purpose of Inheritance
- Code Re usability
- Method Overriding (Hence, Runtime Polymorphism.)
- Use of Virtual Keyword

Basic Syntax of Inheritance
class Subclass_name : access_mode Superclass_name

While defining a subclass like this, the super class must be already defined or at least declared before the subclass declaration.
Access Mode is used to specify, the mode in which the properties of superclass will be inherited into subclass, public, private or protected.

Access Control and Inheritance
A derived class can access all the non-private members of its base class. Thus base-class members that should not be accessible to the member functions of derived classes should be declared private in the base class.

Access
1. same class can access all (public, private, protected) members.
2. derived class can access only public and protected members.
3. Outside classes can access only public members.

A derived class inherits all base class methods with the following exceptions:
- Constructors, destructors and copy constructors of the base class.
- Overloaded operators of the base class.
- The friend functions of the base class.

Inheritance Visibility Mode
Depending on Access modifier used while inheritance, the availability of class members of Super class in the sub class changes. It can either be private, protected or public.

1) Public Inheritance
This is the most used inheritance mode. In this the protected member of super class becomes protected members of sub class and public becomes public.
class Subclass : public Superclass

2) Private Inheritance
In private mode, the protected and public members of super class become private members of derived class.
class Subclass : Superclass
// By default its private inheritance

3) Protected Inheritance
In protected mode, the public and protected members of Super class becomes protected members of Sub class.
class subclass : protected Superclass

No comments:

Post a Comment