Inheritance
Inheritance
⚫ }
⚫ example
Introduction to Inheritance
⚫ Inheritance is relation
between two classes
which has relation or
commonness.
⚫ The commonness can
have limited
variations or extreem
differences.
⚫ Example
Access Modifiers
⚫ Access Modifiers Keywords:
− private, protected and public
⚫ Private and Protected members are inaccessible
outside a class, BUT, can be accessible using
derived classes and friend classes/functions.
⚫ Protected members help in hiding the data but can
be accessed using derived classes.
⚫ Public are accessible from classes or from outside
of the class using class objects.
Relation between Access Modifiers and
Visibility Modes
⚫ Rules of Visibility in
inheritance
⚫ MyEagle: private MyBirds
⚫ Inherited class MyEagle
⚫ Base Class MyBirds
⚫ Access Specifier: private
⚫ Default mode means when no
accessibility mode is specified
⚫ Default mode is private
⚫ e.g. MyEagle: MyBirds
Rules of accessibility: visibility
⚫ Rule 1: Derived Class: (Default visibility ) Private Base Class
− Private variables are accessible only to the member functions of the given
base class and not accessible to the members of a derived class.
− Private and public members of the base class override as a private
members and can only be accessible to the members of the derived
class only.
− Such private visibility members are accessible within the class only, even if
an object created outside the class is not permitted to access these private
visibility members.
− Even When an object of a derived class accesses these private members
either error occurs or no changes of function operations are reflected.
− class <class_name> {
class ⚫ Class members;
⚫ Example
⚫ Students to take example with Private, Protected
Members
Virtual Base Classes and Abstract Classes
⚫ Sometimes some functions are not provided in base class being unclear of
implementation, for example polygon, polygon can be of different shapes and varying
edges. So class having function polygon is an abstract class.
⚫ An abstract class is specifically designed to be a base class having atleast one pure virtual
function.
⚫ A pure virtual function is one which uses pure specifier (i.e. = 0) in a declaration of a pure
virtual function.
⚫ A pure virtual function can not have both i.e. pure specifier ( = 0) and function definition.
⚫ IMP ***: Its not possible to use an abstract class as a parameter type, a function return
type, or the type of explicit conversion and nor can it be declared as an object of an
abstract class.
⚫ IMP***: Abstract class can also be defined using struct keyword.
⚫ Hence, an abstract class must have atleast one pure virtual function.
⚫ Example
Virtual Base Classes and Abstract Classes
⚫ Advantage of Abstract class
− It allows to specify a set of methods that must
be implemented by any subclass
− It ensures consistent interface
− Re-usability
− Promotion of polymorphism
− Virtualization is important data hiding technique
⚫ Virtual debit card, Aadhar card etc.