Inheritance
Types of Inheritance
• Single inheritance
• Multiple inheritance
• Hierarchical inheritance
• Multilevel inheritance
• Hybrid inheritance
Defining derived classes
• Derived class inherits some or all the properties of base class
• General format:
class derived-class-name: visibility-mode base-class-name
{
…….//
……// members of derived class
……//
};
Case 1: Base class is privately inherited by a derived class
• The ‘public members’ of the base class become ‘private members’ of
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.
Case 2: Base class is publicly inherited by a derived class
• The ‘public members’ of the base class become ‘public members’ of
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
Single inheritance (public)
#include<iostream>
using namespace std;
class B
{
int a;
public:
int b;
void get_ab();
int get_a(void);
void show_a(void);
}; class D: public B
{
int c;
public:
void mul(void);
void display(void);
};
void B :: get_ab(void){
a=5;b=10; }
int B :: get_a(){
return a; }
void B :: show_a(){
cout <<“a= “<<a<<“\n”; }
void D :: mul(){
c =b* get_a(); }
void D:: display()
{
cout<<“a = “<<get_a()<<“\n”;
cout<<“b = “<<b<<“\n”;
cout<<“c = “<<c<<“\n”;
}
int main()
{
D d;
d.get_ab();
d.mul();
d.show_a();
d.display();
d.b = 20;
d.mul();
d.display();
return 0;
}