INHERITANCE
INHERITANCE
•Provides a way to create a new class from an existing class
•The new class is a specialized version of the existing class
•Inheritance is an ―”is-a” relation, which inherits the attributes and behavior’s from its parent
class.
•For example, dog is an animal. It means animal is a parent class and Dog is the child class.
• The child class ―”Dog” inherits the attributes like age and weight from the parent class ,
which is an animal.
: Definition
• inheritance: a parent-child relationship between classes
■ allows sharing of the behavior of the parent class into its child classes, code sharing
between classes through inheritance
■ child class can add new behavior or override existing behavior from parent. The new
class is a specialized version of the existing class
• All the data and methods available to the parent class also appear in the child
class with the same names
Inheritance terms
• superclass, base class, parent class: terms to describe the parent in the relationship,
which shares its functionality
• subclass, derived class, child class: terms to describe the child in the relationship,
which accepts functionality from its parent
• extend, inherit, derive: become a subclass of another class.
• Methods of the base class are still accessible in the derived class:
• Using scope resolution (::) in C++
• Using the super keyword in Java or Smalltalk
• Using explicit renaming in Eiffel
Class Access Specifiers:- In c++
Class access specification: determines how private, protected, and public members of base
class are inherited by the derived class
1. Public members are visible anywhere the class declaration is in scope.
2. Private members are visible only inside the class‘s methods.
3. Protected members are visible inside methods of the class or its descendants.
• Private members of a base class are never visible in a derived class.
• Protected and public members of a public base class are protected or public, respectively, in a
derived class.
• Protected and public members of a protected base class are protected members of a derived
class.
• Protected and public members of a private base class are private members of a derived class.
Modes of Inheritance
1. Public mode: If we derive a sub class 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 derived class.
2. Protected mode: If we derive a sub class from a Protected base class. Then both
public member and protected members of the base class will become protected in derived
class.
3. Private mode: If we derive a sub class from a Private base class. Then both public
member and protected members of the base class will become Private in derived class.
Note : The private members in the base class cannot be directly accessed in the derived
class, while protected members can be directly accessed. For example, Classes B, C and D
all contain the variables x, y and z in below example. It is just question of access.
// C++ Implementation to show that a derived class
// doesn’t inherit access to private data members.
// However, it does inherit a full parent object
class A
{
public:
int x;
protected:
int y;
private:
int z;
};
class B : public A
// x is public
// y is protected
// z is not accessible from B
};
class C : protected A
// x is protected
// y is protected
// z is not accessible from C
};
class D : private A // 'private' is default for classes
// x is private
// y is private
// z is not accessible from D
};
o Public: When the member is declared as public, it is accessible to all the functions of the
program.
o Private: When the member is declared as private, it is accessible within the class only.
o Protected: When the member is declared as protected, it is accessible within its own
class as well as the class immediately derived from it.
Types of Inheritance:-
Single inheritance is defined as the inheritance in which a derived class is inherited from the
only one base class.
1. #include <iostream>
2. using namespace std;
3. class Account {
4. public:
5. float salary = 60000;
6. };
7. class Programmer: public Account {
8. public:
9. float bonus = 5000;
10. };
11. int main(void) {
12. Programmer p1;
13. cout<<"Salary: "<<p1.salary<<endl;
14. cout<<"Bonus: "<<p1.bonus<<endl;
15. return 0;
16. }
Multilevel Inheritance
Multilevel inheritance is a process of deriving a class from another derived class.
// C++ program to implement
// Multilevel Inheritance
#include <iostream.h>
using namespace std;
// base class
class Vehicle
public:
Vehicle()
cout << "This is a Vehicle" << endl;
};
class fourWheeler: public Vehicle
{ public:
fourWheeler()
cout<<"Objects with 4 wheels are vehicles"<<endl;
};
// sub class derived from two base classes
class Car: public fourWheeler{
public:
car()
cout<<"Car has 4 Wheels"<<endl;
};
// 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
Objects with 4 wheels are vehicles
Car has 4 Wheels
2)
#include <iostream>
using namespace std;
class base //single base class
public:
int x;
void getdata()
cout << "Enter value of x= "; cin >> x;
};
class derive1 : public base // derived class from base class
{
public:
int y;
void readdata()
cout << "\nEnter value of y= "; cin >> y;
};
class derive2 : public derive1 // derived from class derive1
private:
int z;
public:
void indata()
cout << "\nEnter value of z= "; cin >> z;
void product()
cout << "\nProduct= " << x * y * z;
};
int main()
derive2 a; //object of derived class
a.getdata();
a.readdata();
a.indata();
a.product();
return 0;
} //end of program
Output
Enter value of x= 2
Enter value of y= 3
Enter value of z= 3
Product= 18
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 class.
Syntax:
class subclass_name : access_mode base_class1, access_mode base_class2, ....
{
//body of subclass
};
Here, the number of base classes will be separated by a comma (‘, ‘) and access mode for
every base class must be specified.
// C++ program to explain
// multiple inheritance
#include <iostream>
using namespace std;
// first base class
class Vehicle {
public:
Vehicle()
cout << "This is a Vehicle" << endl;
};
// second base class
class FourWheeler {
public:
FourWheeler()
cout << "This is a 4 wheeler Vehicle" << endl;
};
// sub class derived from two base classes
class Car: public Vehicle, public FourWheeler {
};
// 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
This is a 4 wheeler Vehicle
2)
#include<iostream.h>
#include<conio.h>
class student {
protected:
int rno, m1, m2; public:
void get() {
cout << "Enter the Roll no :"; cin>>rno;
cout << "Enter the two marks :"; cin >> m1>>m2;
}};
class sports
protected:
int sm; // sm = Sports mark public:
void getsm() {
cout << "\nEnter the sports mark :"; cin>>sm;
}};
class result : public student, public sports { int tot, avg;
public:
void display() {
tot = (m1 + m2 + sm); avg = tot / 3;
cout << "\n\n\tRoll No : " << rno << "\n\tTotal : "
<< tot;
cout << "\n\tAverage : " << avg;
};
void main() {
esult obj;
obj.get();
obj.getsm();
obj.display();
}
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.
Syntax of Hierarchical inheritance:
1. class A
2. {
3. // body of the class A.
4. }
5. class B : public A
6. {
7. // body of class B.
8. }
9. class C : public A
10. {
11. // body of class C.
12. }
13. class D : public A
14. {
15. // body of class D.
16. }
Hybrid Inheritance
Hybrid inheritance is a combination of more than one type of inheritance.
Consider the following program:
// C++ program demonstrating ambiguity in Multipath Inheritance
#include<iostream.h>
#include<conio.h>
class ClassA
public:
int a;
};
class ClassB : public ClassA
public:
int b;
};
class ClassC : public ClassA
{
public:
int c;
};
class ClassD : public ClassB, public ClassC
public:
int d;
};
void main()
ClassD obj;
//obj.a = 10; //Statement 1, Error
//obj.a = 100; //Statement 2, Error
obj.ClassB::a = 10; //Statement 3
obj.ClassC::a = 100; //Statement 4
obj.b = 20;
obj.c = 30;
obj.d = 40;
cout<< "\n A from ClassB : "<< obj.ClassB::a;
cout<< "\n A from ClassC : "<< obj.ClassC::a;
cout<< "\n B : "<< obj.b;
cout<< "\n C : "<< obj.c;
cout<< "\n D : "<< obj.d;
Output:
A from ClassB : 10
A from ClassC : 100
B : 20
C : 30
D : 40
Dynamic Method Binding
Two alternatives for choosing the method to call:
»according to the types of variables (references) x and y – static method binding (will call the
method of person in both cases)
»according to the types of objects s and p to which x and y refer – dynamic method binding
(will call the methods of student / professor)
•Example (C++):
student s;
professor p;
...
person * x = &s;
person * y = &p;
x->print_mailing_label (); // ??
y->print_mailing_label (); // ??
• Given C++‘s focus on efficiency its default is static method binding.
• Dynamic method binding is done by declaring the method to be virtual
Virtual Function
• A virtual function is a member function
• declared within a base class
• redefined by a derived class (i.e. overriding)
• It can be used to support run-time polymorphism.
Abstract Classes
class person
...
public:
virtual void print_mailing_label () = 0;
...
};
– Abstract method – virtual method with no body
» also called pure virtual method in C++
– Abstract class – it has at least one abstract method
» cannot declare objects of an abstract class, just pointer
– Interface (Java) – class with no other members than abstract methods.
// C++ program to calculate the area of a square and a circle
#include <iostream>
using namespace std;
// Abstract class
class Shape {
protected:
float dimension;
public:
void getDimension() {
cin >> dimension;
// pure virtual Function
virtual float calculateArea() = 0;
};
// Derived class
class Square : public Shape {
public:
float calculateArea() {
return dimension * dimension;
};
// Derived class
class Circle : public Shape {
public:
float calculateArea() {
return 3.14 * dimension * dimension;
};
int main() {
Square square;
Circle circle;
cout << "Enter the length of the square: ";
square.getDimension();
cout << "Area of square: " << square.calculateArea() << endl;
cout << "\nEnter radius of the circle: ";
circle.getDimension();
cout << "Area of circle: " << circle.calculateArea() << endl;
return 0;