0% found this document useful (0 votes)
53 views

Module6 Lect1,2,3,4,5,6

Inheritance allows one class to inherit properties from another class. A derived or child class inherits characteristics from its parent or base class, including methods and data. Inheritance creates an "is-a" relationship where the child class is a more specific type of the parent. There are different access specifiers like public, private, and protected that determine accessibility of inherited members. Inheritance promotes code reuse and is a fundamental technique in object-oriented design.

Uploaded by

KBS Srikar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

Module6 Lect1,2,3,4,5,6

Inheritance allows one class to inherit properties from another class. A derived or child class inherits characteristics from its parent or base class, including methods and data. Inheritance creates an "is-a" relationship where the child class is a more specific type of the parent. There are different access specifiers like public, private, and protected that determine accessibility of inherited members. Inheritance promotes code reuse and is a fundamental technique in object-oriented design.

Uploaded by

KBS Srikar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

Inheritance

Inheritance
• Inheritance is a fundamental object-oriented design technique used to create and organize
reusable classes.
• Inheritance is the ability of one class to inherit the properties of another class.
• A new class can be created from an existing class.
• The existing class is called BASE CLASS or SUPER CLASS and the new class is called DERIVED CLASS
or SUB CLASS.
• As the name implies, the child inherits characteristics of the parent
• Child inherits the methods and data defined by the parent class
• We can refer to these inherited methods and variables as if they were declared locally in the class

• Example:

Car inherits from another class vehicle


BCA inherits from another class MCA
UML Generalization

• Inheritance relationships are shown in a UML class diagram using a solid arrow with an unfilled
triangular arrowhead pointing to the parent class
• Proper inheritance creates an is-a relationship, meaning the child is a more specific version of the
parent
Why and when to use inheritance?

The methods fuelAmount(), capacity(), applyBrakes() will be same for all of


the three classes and same code has to be written three times
Using inheritance
Arrange concepts into an inheritance hierarchy
• Concepts at higher levels are more general
• Concepts at lower levels are more specific (inherit properties
of concepts at higher levels)

Vehicle

Wheeled vehicle Boat

Car Bicycle

2-door 4-door
Advantages of inheritance

• When a class inherits from another class, there are three benefits:

(1) You can reuse the methods and data of the existing class
(2) You can extend the existing class by adding new data and new
methods
(3) You can modify the existing class by overloading its methods
with your own implementations
Inheritance is the property that allows the
reuse of an existing class to build a new class

Base Class Derived class


Methods Base class methods
and +
Properties Additional methods
Access specifier
• Public - The members declared as Public are accessible
from outside the Class through an object of the class.
• Protected - The members declared as Protected are
accessible from outside the class BUT only in a class
derived from it.
• Private - These members are only accessible from
within the class. No outside Access is allowed.
Accessibility of base class member
Access Specifier Accessible from Accessible from Accessible from
own class derived object outside class
class(inheritable)

Public Yes Yes Yes

Protected Yes Yes No

Private Yes No No
Inheritance

Single Inheritance Hierarchical


Inheritance

Multilevel Multiple Inheritance


Inheritance
Single Inheritance
• A class can be derived from a single base class is called single inheritance.
• derived class is inherited from the only one base class.

Person

Employee
Syntax of single inheritance in C++
class Base_Class
{
// class definition
};
class Derived_Class: visibility mode Base_Class_name
{
// body of the derived class
};
int main()
{
Base_Class obj1;
Derived_Class obj2;
// code
}
Example for Single Inheritance
# include <iostream> int main()
using namespace std; {
class B
D n;
{
public: n.x=100;
int x; n.y=200;
}; cout<<"\n x="<<n.x;
class D: public B cout<<"\n y=" <<n.y;
{ n.disp();
public: }
int y;
void disp()
{
cout<<"\n access base members:"<<x;
}
};
Modes of inheritance in C++

1. class ABC : private XYZ //private derivation


{ }
2. class ABC : public XYZ //public derivation
{ }
3. class ABC : protected XYZ //protected derivation
{ }
4. class ABC: XYZ //private derivation by default
{ }
Modes of inheritance in C++

Public mode:
• In the public mode of inheritance, when a child class is derived from the
base or parent class, then the public member of the base class or parent
class will become public in the child class also, in the same way, the
protected member of the base class becomes protected in the child class,
and private members of the base class are not accessible in the derived
class.
Protected mode:
• In protected mode, when a child class is derived from a base class or
parent class, then both public and protected members of the base class will
become protected in the derived class, and private members of the base
class are again not accessible in the derived class. In contrast, protected
members can be easily accessed in the derived class.
Modes of inheritance in C++

Private mode
In private mode, when a child class is derived from a base class, then
both public and protected members of the base class will become
private in the derived class, and private members of the base class are
again not accessible in the derived class.
Modes of inheritance

class A
{
public:
int x; class C : protected A
{
protected: // x is protected
int y; // y is protected
// z is not accessible from C
private: };
int z;
}; class D : private A // 'private' is default for classes
{
// x is private
class B : public A // y is private
// z is not accessible from D
{
};
// x is public
// y is protected
// z is not accessible from B
};
# include <iostream> int main()
using namespace std; {
class B D n;
{ n.x=100;
public: n.y=200;
int x; cout<<"\n x="<<n.x;
}; cout<<"\n y=" <<n.y;
n.disp();
class D: private B }
{
public:
int y;
void disp()
{
cout<<"\n access base members:"<<x;
}
};
Example for Single Inheritance
# include <iostream> class D: public B
using namespace std; {
class B public:
{ int y;
private:
int x; D()
public: {
B() y=200;
{ }
x=100; void disp()
} {
void show() cout<<"\n derived class members:"<<y; }
{ };
cout<<"\n access base members:"<<x; int main()
} {
}; D n;
n.show();
n.disp();
}
Employee processing using single Inheritance
#include<iostream.h> class salary : public emp {
#include<conio.h> float bp, hra, da, pf, np;
public:
class emp { void get1() {
public: cout << "Enter the basic pay:";
cin>>bp;
int eno; cout << "Enter the Humen Resource Allowance:";
char name[20], des[20]; cin>>hra;
cout << "Enter the Dearness Allowance :";
void get() { cin>>da;
cout << "Enter the Profitablity Fund:";
cout << "Enter the employee number:"; cin>>pf;
cin>>eno; }
cout << "Enter the employee name:";
void calculate() {
cin>>name; np = bp + hra + da - pf;
cout << "Enter the designation:"; }
cin>>des;
} void display() {
cout << eno << "\t" << name << "\t" << des <<
}; "\t" << bp << "\t" << hra << "\t" << da << "\t" << pf <<
"\t" << np << "\n";
} };
Continuation of Previous Program
void main() {
int i, n;
char ch;
salary s[10];
cout << "Enter the number of employee:";
cin>>n;
for (i = 0; i < n; i++) {
s[i].get();
s[i].get1();
s[i].calculate();
}
cout << "\ne_no \t e_name\t des \t bp \t
hra \t da \t pf \t np \n";
for (i = 0; i < n; i++) {
s[i].display();
}
}
Multilevel Inheritance
A derived class is created from another derived class.

Vehicle Person

Car Employee

Racing car Part time


Employee
#include<iostream>
using namespace std; class Car:public Four_wheeler
class Vehicle {
{ public:
public: Car()
Vehicle() {
{ cout<<"\n I am in derived class
cout<<"\n I am in base class constructor"; constructor";
} }
}; };
class Four_wheeler: public Vehicle int main()
{ {
public: Car n;
Four_wheeler() return 0;
{ }
cout<<"\n I am in intermediate class
constructor";
}
};
#include <iostream> class BabyDog: public Dog
using namespace std; {
class Animal { public:
public: void weep() {
void eat() cout<<"Weeping...";
{ }
cout<<"Eating..."<<endl; };
} int main(void)
}; {
class Dog: public Animal BabyDog d1;
{ d1.eat();
public: d1.bark();
void bark(){ d1.weep();
cout<<"Barking..."<<endl; return 0;
} }
};
Multiple Inheritance
It is the process of creating new class from more than one base classes.
Syntax :
class subclass_name : access_mode base_class1, access_mode base_class2, ....
{
private :
// members;
protected :
// members;
public :
//memebers;
};
Person Employee

Teacher
class C : public A,public B
#include <iostream>
using namespace std; { int main()
class A {
public: C c;
{
protected: void display() c.get_a(10);
int a; c.get_b(20);
{ c.display();
public:
void get_a(int n) cout << "The value of a is : " <<a<<endl;
{ return 0;
cout << "The value of b is : " <<b<<endl;
a = n; }
} cout<<"Addition of a and b is : "<<a+b;
}; }

class B
};
{
protected:
int b;
public:
void get_b(int n)
{
b = n;
}
};
#include<iostream> class statement : public student, public sports
using namespace std; {
int tot, avg;
public:
class student {
protected: void display() {
int rno, m1, m2; tot = (m1 + m2 + sm);
public: avg = tot / 3;
cout << "\n\n\tRoll No : " << rno << "\n\tTotal : " <<
void get() { tot;
cout << "Enter the Roll no :"; cout << "\n\tAverage : " << avg;
cin>>rno; }
cout << "Enter the two marks :"; };
cin >> m1>>m2;
}
}; int main()
{
class sports statement obj;
{ obj.get();
protected: obj.getsm();
int sm; // sm = Sports mark obj.display();
public: return 0;
void getsm() { }
cout << "\nEnter the sports mark :";
cin>>sm;

}
};
Hierarchical Inheritance
If more than one class is inherited from a base class, it's known as hierarchical
inheritance. In general, all features that are common in child classes are included
in base class in hierarchical inheritance.

Employee

Permanent Temporary
Employee Employee
For example, Physics, Chemistry, Biology are derived from Science class. Similarly, Dog, Cat, Horse are derived
from Animal class.
Syntax of Hierarchical Inheritance
class base_class
{
... .. ...
}

class first_derived_class: public base_class


{
... .. ...
}

class second_derived_class: public base_class


{
... .. ...
}

class third_derived_class: public base_class


{
... .. ...
}
Ex: Hierarchical Inheritance

class Cat : public Animal


#include <iostream> {
using namespace std; public:
void meow()
class Animal {
{ cout << "Derived-II am a Cat. Meow." << endl;
public: }
};
void info()
{ int main() {
cout << "Base-I am an animal." << // Create object of Dog class
endl; Dog dog1;
cout << "Dog Class:" << endl;
} dog1.info(); // Parent Class function
}; dog1.bark();
class Dog : public Animal
// Create object of Cat class
{ Cat cat1;
public: cout << "\nCat Class:" << endl;
void bark() cat1.info(); // Parent Class function
{ cat1.meow();

cout << "Derived-I am a Dog. Woof return 0;


woof." << endl; }
}
};
Hierarchical Inheritance
#include <iostream>
using namespace std; int main()
class A //single base class
{ {
public: B obj1; //object of derived class B
int x, y;
void getdata() C obj2; //object of derived class C
{
obj1.getdata();
cout << "\nEnter value of x and y:\n"; cin >> x >> y;
} }; obj1.product();
class B : public A //B is derived from class base
obj2.getdata();
{
public: obj2.sum();
void product()
{ return 0;
cout << "\nProduct= " << x * y; } //end of program
}
};
class C : public A //C is also derived from class base
{
public:
void sum()
{
cout << "\nSum= " << x + y;
} };
Same Data Member Name in Base and Derived Class
#include<iostream> class B:public A
using namespace std; { main()
class A int x; {
{ public: B b;
protected: B(){x=10;} A a;
int x; a.print();
public: void print() b.print();
A() { }
{x=5;} cout<<"inside B "<<x<<endl; }
void print() };
{
cout<<"inside A
"<<x<<endl;}
};
Hybrid Inheritance
• Hybrid Inheritance is implemented by combining more than one type of inheritance.
• Hybrid is nothing but the combination of Multilevel and multiple Inheritance.
• The hybrid inheritance in C++ is also called multipath inheritance, where one derived class can inherit properties of
the base class in different paths.
• Here a child class is derived from one or more combinations of single, hierarchical, and multilevel inheritances. This
inheritance is adopted for programs to mix different types of inheritance
• The diagram represents the hybrid
combination of two inheritances; the
single inheritance and the multiple
inheritances.

• Here, in single inheritance, class B is


derived from class A. Similarly, in multiple
inheritances, Class D is inherited from
multiple classes. Here class B and class C.

• So, a mix of single inheritance and


multiple inheritances forms a hybrid
inheritance.
#include <iostream> class Ferrari: public Car, public Racing
using namespace std;
class Vehicle {
{ public:
public: Ferrari()
Vehicle()
{ {
cout<<"\n this is a vehicle-base class"; cout<<"\n this is the derived class-ferrari";
} }
};
};
class Car : public Vehicle
{
int main()
public:
Car() {
{ Ferrari n;
cout<<"\n this is a Car class-intermediate baseclass1";
} return 0;
}; }

class Racing
{
public:
Racing()
{
cout<<"\n this is a Racing class-intermediate baseclass2";
}
};
How to call a parent class function from derived class function in C++?
#include <iostream> int main() {
using namespace std;
class p1 d1 d;
{
public: d.first();
void first()
{ return 0;
cout << "\nThe parent class p1 function is called.";
} }
};
class d1 : public p1
{
public:
void first()
{
cout << "The derived class d1 function is called.";
p1::first();
}
};
Multi-Path Inheritance
• When a class inherits the properties of another class two or more times through two or more
different paths it is known as multipath inheritance.
• When a class is derived from two base classes and those two base classes have one common
base class is called multipath inheritance
• The diamond problem occurs when two superclasses of a class have a common base class.
• To avoid this ambiguity scope resolution operator is used.
• The properties are inherited more than once, so more memory is consumed and ambiguity
(doubt) gets created, in order to avoid this extra consumption of memory and ambiguity, we
declare the base class as virtual while giving the definition of the derived class.
To avoid the ambiguity problem
#include<iostream> Ex: MULTIPATH Inheritance
class ClassA { int main()
public: {
int a; ClassD obj;
}; // obj.a = 10; // Statement 1, Error [ambiguous]
// obj.a = 100; // Statement 2, Error [ambiguous]
class ClassB : public ClassA {
public: obj.ClassB::a = 10; // Statement 3 OUTPUT
int b; obj.ClassC::a = 100; // Statement 4 a from ClassB : 10
}; a from ClassC : 100
obj.b = 20; b : 20
class ClassC : public ClassA { obj.c = 30; c : 30
public: obj.d = 40; d : 40
int c; cout << " a from ClassB : " << obj.ClassB::a;
}; cout << "\n a from ClassC : " << obj.ClassC::a;

class ClassD : public ClassB, public ClassC cout << "\n b : " << obj.b;
{ cout << "\n c : " << obj.c;
public: cout << "\n d : " << obj.d << '\n';
int d; }
};
VIRTUAL BASE CLASS
As we can see from the figure that data
members/function of class A are inherited twice to
class D. One through class B and second through class
C. When any data / function member of class A is
accessed by an object of class D, ambiguity arises as to
which data/function member would be called? One
inherited through B or the other inherited through C.
This confuses compiler and it displays error.
Syntax for Virtual Base Classes:

Syntax 1:
class B : virtual public A
{
};

Syntax 2:
class C : public virtual A
{
};
using namespace std;
class A { NOTE :
public: • In C++, you can use virtual inheritance to resolve ambiguity in
int a; inheritance. Virtual inheritance is a way of specifying that a class
A() // constructor should be inherited virtually,
{
a = 10;
} • virtual can be written before or after the public. Now only one
}; copy of data/function member will be copied to class C and class B
class B : public virtual A and class A becomes the virtual base class.
{ • The virtual base class is a concept used in multiple inheritances to
}; prevent ambiguity between multiple instances.
class C : public virtual A
{ • On declaring the base class as virtual the properties of the base
};
class are inherited only once and hence no extra memory is
class D : public B, public C
{ consumed and the problem of ambiguity automatically gets
}; solved.
int main()
{ • The class A has just one data member a which is public. This class
D object; // object creation of class d is virtually inherited in class B and class C. Now class B and class C
cout << "a = " << object.a << endl; becomes virtual base class and no duplication of data member a is
return 0; done.
}
#include <iostream>
using namespace std; int main()
{
class A { D object;
public: object.show();
void show() }
{
cout << "Hello from A \n";
}
};
Output:
class B : public virtual A { Hello from A
};

class C : public virtual A {


};

class D : public B, public C {


};
Order of Constructor Call

Base class constructors are always called in the derived class constructors.
Whenever you create derived class object, first the base class default
constructor is executed and then the derived class's constructor finishes
execution.

Points to Remember
1.Whether derived class's default constructor is called or parameterised is
called, base class's default constructor is always called inside them.

2.To call base class's parameterised constructor inside derived class's


parameterised constructor, we must mention it explicitly while declaring
derived class's parameterized constructor.
Base class Parameterized Constructor in Derived class Constructor
#include<iostream> int main()
using namespace std; {
class Base
{ Derived d(10);
int x;
public: return 0;
Base(int i) }
{
x=i;
cout<<"Base parameterized constructor and output
x="<<x<<endl;
}
};
class Derived :public Base
{
int y;
public:
Derived(int j):Base(j)
{
y=j;
cout<<"derived parameterised constructor and
y="<<y<<endl;
}
};
Constructor call in Multiple Inheritance
Its almost the same, all the Base class's constructors are called inside derived class's
constructor, in the same order in which they are inherited.
class A : public B, public C ;
In this case, first class B constructor will be called, then class C constructor and then class A
constructor.

You might also like