0% found this document useful (0 votes)
4 views25 pages

UNIT 4 Inheritance

Inheritance is a key concept in object-oriented programming that allows a class to inherit properties and methods from another class, promoting code reuse and faster implementation. C++ supports various types of inheritance including single, multiple, multilevel, hierarchical, and hybrid inheritance, each with specific syntax and access specifiers (public, protected, private) that control member accessibility. The document provides examples of C++ code demonstrating these inheritance types and their access controls.

Uploaded by

venkat
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views25 pages

UNIT 4 Inheritance

Inheritance is a key concept in object-oriented programming that allows a class to inherit properties and methods from another class, promoting code reuse and faster implementation. C++ supports various types of inheritance including single, multiple, multilevel, hierarchical, and hybrid inheritance, each with specific syntax and access specifiers (public, protected, private) that control member accessibility. The document provides examples of C++ code demonstrating these inheritance types and their access controls.

Uploaded by

venkat
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT-4: INHERITANCE

Inheritance

Inheritance is one of the most important concepts of object-oriented


programming. It is a feature that allows a class to inherit properties and
attributes from another class, enabling developers to reuse the code as the
derived class can reuse base class members through inheritance. It also
speeds up implementation.

While creating a class, a programmer can inherit a new class from an existing
class rather than writing new data members and member functions from
scratch. The existing class is the base class and the new class is called the
derived class.

Inheritance in C++: Definition

Inheritance in C++ is the capability of a class to derive methods and


properties from another class. It is an important feature of object-oriented
programming, in which a new class is derived from the existing class.

The new class is called the derived or child class and it can have additional
features, along with the characteristics inherited from the base class. The
existing class is known as the parent class.

Syntax:

class derived_class_name : access-specifier base_class_name

// body ....

};
Here,

class is the keyword to create a new class.

derived_class_name is the name of the new class that inherits from the
existing class.

access-specifier is used to specify the access mode, which can be public,


private, or protected. By default, it is private.

base-class-name is the name of the base class.

//Write C++ Program to demonstrate the inheritance.

#include <iostream>
using namespace std;
class Person
{
public:
void showName()
{
cout << "Name: BHARAT" << endl;
}
};
class Student : public Person
{
public:
void showRoll()
{
cout << "Roll No: 101" << endl;
}};
int main()
{
Student s;
[Link](); // Inherited from Person
[Link](); // From Student
return 0;
}
Student inherits from Person using public inheritance.
So Student gets access to showName() of Person.
It also has its own method showRoll().
//sample2 example of Inheritance
#include <iostream>
using namespace std;
// Base class
class Vehicle
{
public:
void start()
{
cout << "Vehicle started" << endl;
}
};
// Derived class
class Car : public Vehicle
{
public:
void drive()
{
cout << "Car is driving" << endl;
}
};
int main()
{
Car myCar;
[Link](); // Inherited from Vehicle
[Link](); // Defined in Car
return 0;
}
Base Class and Derived Class in C++ Inheritance
A class can be derived from more than one class. This means that a new class
can inherit data and functions from more than one class. We can define a
derived class by using a class derivation list to mention the base class. The
derivation list names one or more base classes.
Syntax:
class derived-class: access-specifier base-class

Base Class- Also known as a parent class, it is the pre-existing class from
which the child class inherits its attributes and properties. Multiple child
classes can inherit from a single parent class, or a single child class can
inherit from multiple parent classes.

Derived Class- Also known as a child class, it is the new class that is derived
from the existing class. It inherits characteristics of the parent class and
accesses the data members of the parent class based on the visibility mode
specified while declaring the child class. It inherits properties of the base
class and can have some additional properties as well.
Access Specifiers:
The access specifiers in C++ inheritance can be public, private, or protected.
A subclass can access non-private members of the base class. So, if you don’t
want the base class members to be accessible to derived class member
functions, declare them as private.

In C++ inheritance, the protected access modifier is especially relevant. The


protected members are not accessible outside of a class but can be accessed
by the derived class and friend classes. Use protected members if you want
to hide the class data but still want the derived class to inherit the data.

The three modes of inheritance that control the access level of inherited
members of the parent class in the child class.

I. Public

II. Protected

III. Private

Public Inheritance Mode


The members declared as public in the base class remain public in the
derived class. This means that if we derive a subclass from the public base
class, its public members are inherited by the derived class as they are.
Similarly, protected members of the base class will be protected in the
derived class. Public members are accessible by the derived class and other
classes.
//C++ Program to demonstrate the Public access specifiers.
#include <iostream>
using namespace std;
class Employee
{
public:
string name = "Virat";

protected:
int salary = 50000;
};
class Developer : public Employee
{
public:
void showInfo() {
cout << "Name: " << name << endl; // Public member
cout << "Salary: " << salary << endl; // Protected member
}
};
int main()
{
Developer d;
[Link](); // Accessing through derived class
// cout << [Link]; // Accessible (public)
// cout << [Link]; // Error: salary is protected
return 0;
}
• name is public in base → remains public in derived → accessible in
main.
• salary is protected in base → remains protected in derived →
accessible only inside the class, not in main().
• This is an example of public inheritance mode, where:
• Public stays public
• Protected stays protected

Protected Inheritance Mode


If we inherit a derived class from a protected base class, the public and
protected members of the base class will remain protected in the derived
class. The protected members are accessible by the derived class and its
member functions. Also, the protected members can be inherited and are
accessible to inherited classes. However, they are not accessible to the
objects of the derived class outside the class.

//C++ Program to demonstrate the Protected access Specifier.


#include <iostream>
using namespace std;
class Device
{
public:
string model = "Vivo50";

protected:
int batteryLife = 90; // in percentage
};
class Smartphone : protected Device
{
public:
void showDetails()
{
cout << "Model: " << model << endl;
cout << "Battery: " << batteryLife << "%" << endl;
}
};

int main()
{
Smartphone phone;
[Link](); // Allowed: through member function
// cout << [Link]; // Error: model is protected in Smartphone
// cout << [Link]; // Error: batteryLife is protected
return 0;
}

• model is public in Device, but becomes protected in Smartphone (due


to protected inheritance).
• batteryLife is protected in base and stays protected.
• Both are accessible inside Smartphone, but not directly through the
object in main().

Private Inheritance Mode

If a class is derived from the private base class, public and protected
members of the base class become private in the derived class. Hence,
it restricts the access to these members outside the derived class. It is
the default mode applied when we don’t mention the access specifier.
Private members can be accessed only by the member functions of the
derived class.
//C++ Program to demonstrate the Private access specifier.
#include <iostream>
using namespace std;
class Box
{
public:
string content = "gold";

protected:
int weight = 5;
};
class Locker : private Box
{
public:
void showLocker()
{
cout << "Content: " << content << endl;
cout << "Weight: " << weight << "kg" << endl;
}
};
int main()
{
Locker l;
[Link](); // Works: accessed via member function
// cout << [Link]; // Error: content is private in Locker
// cout << [Link]; // Error: weight is private in Locker
return 0;
}
content is public in Box → becomes private in Locker.
weight is protected in Box → also becomes private in Locker.
Both can be used only inside Locker class, not accessible from main().

Fig: Access Specifiers Scope.


Types Of Inheritance in C++
Based on the relationship between the base class and the derived class,
inheritance in C++ can be of the following types:
1. Single inheritance
2. Multiple inheritance
3. Multilevel inheritance
4. Hierarchical inheritance
5. Hybrid inheritance
1. Single Inheritance:
It is a single class inherits from one base class. Based on the visibility mode
mentioned during inheritance, the data members of the base class are
accessed by the derived class.
Syntax:
class subclassname : accessspecifier superclassname
{
//class specific code;
};
//C++ Program to demonstrate the single-level inheritance:
#include <bits/stdc++.h>
using namespace std;

class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle"<< endl;
}
};

// Sub class derived from a single base classes


class Car : public Vehicle
{
public:
Car()
{
cout << "This Vehicle is Car"<< endl;
}
};

int main()
{
// Creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}
2. Multiple Inheritance:
Multiple Inheritance is a feature of C++ where a class can inherit from more
than one class. i.e one subclass is inherited from more than one base class.

Multiple inheritance is a type of inheritance in which a class derives from


more than one class. As shown in the above diagram, class C is a subclass
that has class A and class B as its parent.

In a real-life scenario, a child inherits from their father and mother. This can
be considered an example of multiple inheritance.
// C++ Program to demonstrate the Multiple inheritance
#include <iostream>
using namespace std;
//multiple inheritance example
class student_marks
{
protected:
int rollNo, marks1, marks2;
public:
void get()
{
cout << "Enter the Roll No.: ";
cin >> rollNo;
cout << "Enter the two highest marks: ";
cin >> marks1 >> marks2;
}
};
class cocurricular_marks
{
protected:
int comarks;
public:
void getsm()
{
cout << "Enter the mark for CoCurricular Activities: ";
cin >> comarks;
}
};
//Result is a combination of subject_marks and cocurricular activities marks
class Result : public student_marks, public cocurricular_marks
{
int total_marks, avg_marks;
public:
void display()
{
total_marks = (marks1 + marks2 + comarks);
avg_marks = total_marks / 3;
cout << "\nRoll No: " << rollNo << "\nTotal marks: " << total_marks;
cout << "\nAverage marks: " << avg_marks;
}
};
int main()
{
Result res;
[Link](); //read subject marks
[Link](); //read cocurricular activities marks
[Link](); //display the total marks and average marks
}

Output:
Enter the Roll No.: 25
Enter the two highest marks: 40 50
Enter the mark for CoCurricular Activities: 30

Roll No: 25
Total marks: 120
Average marks: 40
3. Multi-level Inheritance:
In multilevel inheritance, a class is derived from another derived class. This
inheritance can have as many levels as long as our implementation doesn’t
go wayward. In the above diagram, class C is derived from Class B. Class B is
in turn derived from Class A.

The following example illustrates Multilevel Inheritance in C++:

#include <iostream>
using namespace std;
class electronicDevice
{
public:
// constructor of the base class 1
electronicDevice()
{
cout << "I am an electronic device.\n\n";
}

};
class Computer: public electronicDevice
{
public:
// constructor of the base class 2
Computer()
{
cout << "I am a computer.\n\n";
}
};

class Linux_based : public Computer


{
public:
// constructor of the derived class
Linux_based()
{
cout << "I run on Linux.\n\n";;
}
};

int main()
{
// create object of the derived class
Linux_based obj; // constructor of base class 1,

return 0;

4. Hierarchical Inheritance
The inheritance in which a single base class inherits multiple derived classes
is known as the Hierarchical Inheritance. This inheritance has a tree-like
structure since every class acts as a base class for one or more child classes.
The visibility mode for each derived class is specified separately during the
inheritance and it accesses the data members accordingly.
In hierarchical inheritance, more than one class inherits from a single base
class as shown in the representation above. This gives it a structure of a
hierarchy.
//C++ Program to hierarchical inheritance.
#include <iostream>
using namespace std;
class Shape // shape class -> base class
{
public:
int x,y;
void get_data(int n,int m)
{
x= n;
y = m;
}
};
class Rectangle : public Shape // inherit Shape class
{
public:
int area_rect() {
int area = x*y;
return area;
}
};
class Triangle : public Shape // inherit Shape class
{
public:
int triangle_area() {
float area = 0.5*x*y;
return area;
}
};
class Square : public Shape // inherit Shape class
{
public:
int square_area() {
float area = 4*x;
return area;
}
};
int main()
{
Rectangle r;
Triangle t;
Square s;
int length,breadth,base,height,side;
cout << "Enter the length and breadth of a rectangle: ";
cin>>length>>breadth;
r.get_data(length,breadth);
int rect_area = r.area_rect();
cout << "Area of the rectangle = " <<rect_area<< std::endl;
cout << "Enter the base and height of the triangle: "; cin>>base>>height;
t.get_data(base,height);
float tri_area = t.triangle_area();
cout <<"Area of the triangle = " << tri_area<<std::endl;
cout << "Enter the length of one side of the square: "; cin>>side;
s.get_data(side,side);
int sq_area = s.square_area();
cout <<"Area of the square = " << sq_area<<std::endl;
return 0;
}
Hybrid Inheritance:
Hybrid inheritance is usually a combination of more than one type of
inheritance. In the above representation, we have multiple inheritance (B, C,
and D) and multilevel inheritance (A, B, and D) to get a hybrid inheritance.
//C++ Program to //Hybrid inheritance = multilevel + multilpe
#include <iostream>
#include <string>
using namespace std;
class student{ //First base Class
int id;
string name;
public:
void getstudent()
{
cout << "Enter student Id and student name";
cin >> id >> name;
}
};
class marks: public student
{ //derived from student
protected:
int marks_math,marks_phy,marks_chem;
public:
void getmarks()
{
cout << "Enter 3 subject marks:";
cin >>marks_math>>marks_phy>>marks_chem;
}
};
class sports
{
protected:
int spmarks;
public:
void getsports()
{
cout << "Enter sports marks:";
cin >> spmarks;
}
};
class result : public marks, public sports{
int total_marks;
float avg_marks;
public :
void display(){
total_marks=marks_math+marks_phy+marks_chem;
avg_marks=total_marks/3.0;

cout << "Total marks =" << total_marks << endl;


cout << "Average marks =" << avg_marks << endl;
cout << "Average + Sports marks =" << avg_marks+spmarks;
}
};

int main(){
result res;//object//
[Link]();
[Link]();
[Link]();
[Link]();
return 0;
}
friend function:
A friend function can access the private and protected data of a class. We
declare a friend function using the friend keyword inside the body of the
class.
Syntax:
class className {
... .. ...
friend returnType functionName(arguments);
... .. ...
}

// C++ program to demonstrate the working of friend function

#include <iostream>
using namespace std;

class Distance {
private:
int meter;

// friend function
friend int addFive(Distance);

public:
Distance() : meter(0) {}

};
// friend function definition
int addFive(Distance d) {

//accessing private members from the friend function


[Link] += 5;
return [Link];
}

int main() {
Distance D;
cout << "Distance: " << addFive(D);
return 0;
}

You might also like