Lecture 1 (Module 3)
Lecture 1 (Module 3)
Inheritance
Inheritance
• The new class created is called “derived class” or “child class” and the
existing class is known as the “base class” or “parent class”.
Sub Class vs Super Class:
• Sub Class: The class that inherits properties from another class is
called Subclass or Derived Class.
//body
}
Modes of Inheritance:
• Public Mode: If we derive a subclass from a public base class. Then
the public member of the base class will become public in the derived
class and protected members of the base class will become protected
in the derived class.
• Protected Mode: If we derive a subclass from a Protected base class.
Then both public members and protected members of the base class
will become protected in the derived class.
• Private Mode: If we derive a subclass from a Private base class. Then
both public members and protected members of the base class will
become Private in the derived class.
Modes of Inheritance:
Types of Inheritance:
• Single inheritance
• Multilevel inheritance
• Multiple inheritance
• Hierarchical inheritance
• Hybrid inheritance
Single inheritance
Syntax:
class subclass_name : access_mode base_class
{
// body of subclass
};
Single inheritance
Single Inheritance example 1:
#include<iostream>
using namespace std;
// base class
class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle\n";
}
};
};
// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}
Output:
This is a Vehicle
Single Inheritance example 2:
#include<iostream>
using namespace std;
class A
{
protected:
int a;
public:
void set_A()
{
cout<<"Enter the Value of A=";
cin>>a;
}
void disp_A()
{
cout<<endl<<"Value of A="<<a;
}
};
class B: public A
{
int b,p;
public:
void set_B()
{
set_A();
cout<<"Enter the Value of B=";
cin>>b;
}
void disp_B()
{
disp_A();
cout<<endl<<"Value of B="<<b;
}
void cal_product()
{
p=a*b;
cout<<endl<<"Product of "<<a<<" * "<<b<<" = "<<p;
}
};
int main()
{
B b;
b.set_B();
b.cal_product();
return 0;
}
OUTPUT:
Product of 3 * 4 = 12