C++ Inheritance
C++ Inheritance
By:
Dr. Shweta Jain
Head Coordinator, Data Science
C++ Inheritance
Sub Class: The class that inherits properties from another class is called Sub
class or Derived Class.
Super Class: The class whose properties are inherited by sub class is called
Base Class or Super class.
Why and when to use inheritance?
Syntax for Inheritance and Access Modes:
In C++, there are three access specifiers:
● public - members are accessible from outside the class
● private - members cannot be accessed (or viewed) from outside the
class
● protected - members cannot be accessed from outside the class,
however, they can be accessed in inherited classes. You will learn more
about Inheritance later.
Syntax:
class subclass_name : access_mode base_class_name
{
//body of subclass
};
Code 1: Demonstration of Inheritance
// C++ program to demonstrate //main function
// implementation of Inheritance int main()
{
#include <iostream.h>
using namespace std; Child obj1;
Types of
Inheritance
In single inheritance, a class is allowed to inherit from only one class. i.e. one sub
class is inherited by one base class only.
Syntax:
class subclass_name : access_mode base_class
{
//body of subclass
};
2. Multiple Inheritance
Multiple Inheritance is a feature of C++ where a class can inherit from more than
one classes. i.e one sub class is inherited from more than one base classes.
Syntax:
In this type of inheritance, a derived class is created from another derived class.
4. Hierarchical Inheritance
In this type of inheritance, more than one sub class is inherited from a single base
class. i.e. more than one derived class is created from a single base class.
5. Hybrid (Virtual) Inheritance
A derived class with two base classes and these two base classes have one
common base class is called multipath inheritance. An ambiguity can arise in this
type of inheritance.