Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Module 6 - Inheritance

The document provides an overview of inheritance in C++, detailing various types such as single, multiple, multilevel, hierarchical, and hybrid inheritance. It explains the concept of inheritance as a means to create a derived class from a base class, emphasizing code reusability and the is-a relationship. Additionally, it covers access specifiers and the order of constructor execution when a class is derived from another class.

Uploaded by

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

Module 6 - Inheritance

The document provides an overview of inheritance in C++, detailing various types such as single, multiple, multilevel, hierarchical, and hybrid inheritance. It explains the concept of inheritance as a means to create a derived class from a base class, emphasizing code reusability and the is-a relationship. Additionally, it covers access specifiers and the order of constructor execution when a class is derived from another class.

Uploaded by

gigachadmaleme
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Module 6 -

Inheritance
Inheritance - Types of Inheritance: Single inheritance, Multiple
Inheritance, Multi-level Inheritance, Hierarchical Inheritance -
Multipath Inheritance - Inheritance and constructors.
Inheritance
• It
allows us to create a new class (derived class) from an
existing class (base class).
• It provides reusability of code.
• Thederived class inherits the features from the base
class and can have additional features of its own.
• Inheritance is an is-a relationship. We use inheritance only
if an is-a relationship is present between the two classes.
• A car is a vehicle.
• Orange is a fruit.
• A surgeon is a doctor.
• A dog is an animal.
Inheritance
class Animal {
// eat() function
// sleep() function
};
class Dog : public
Animal
{
// bark() function
};
Notice the use of the keyword public while inheriting Dog from Animal
// C++ program to demonstrate inheritance // derived class
class Dog : public Animal {
#include <iostream>
using namespace std; public:
void bark() {
// base class cout << "I can bark! Woof woof!!"
class Animal { << endl;
}
};
public: int main() {
void eat() { // Create object of the Dog class
cout << "I can eat!" << Dog dog1;
endl;
} // Calling members of the base class
dog1.eat();
dog1.sleep();
void sleep() {
cout << "I can sleep!" << // Calling member of the derived class
endl; dog1.bark();
}
return 0;
}; }
Types of Inheritance
Single inheritance
•A derived class inherits from a single base class
• The simplest type of inheritance
• For example, a dog inherits from an animal class

Syntax:

class subclassname : accessspecifier superclassname


{ //class specific code; };
#include <iostream>
int main()
#include <string>
using namespace std; {
class Animal Dog dog;
{ cout<<"Dog has "<<dog.legs<<"
string name=""; legs"<<endl;
public: cout<<"Dog has "<<dog.tail<<"
int tail=1;
tail"<<endl;
int legs=4;
}; cout<<"Dog ";
class Dog : public Animal dog.voiceAction();
{ }
public: Output:
void voiceAction()
{ Dog has 4 legs
cout<<"Barks!!!"; Dog has 1 tail
} Dog Barks!!!
};
Types of Inheritance

Multiple inheritance
A derived class inherits from more than one base class

Allows a derived class to inherit more properties and


characteristics

class C is a subclass that has class A and


class B as its parent.
class Result : public student_marks, public
cocurricular_marks
#include <iostream> //Result is a combination of subject_marks and
using namespace std; cocurricular activities marks
//multiple inheritance example class Result : public student_marks, public
class student_marks { cocurricular_marks {
protected: int total_marks, avg_marks;
int rollNo, marks1, marks2; public:
public: void display()
void get() { {
cout << "Enter the Roll No.: "; cin >> rollNo; total_marks = (marks1 + marks2 + comarks);
cout << "Enter the two highest marks: "; cin avg_marks = total_marks / 3;
>> marks1 >> marks2; cout << "\nRoll No: " << rollNo << "\nTotal
} marks: " << total_marks;
}; cout << "\nAverage marks: " << avg_marks;
class cocurricular_marks { }
protected: };
int comarks; int main()
public: {
void getsm() { Result res;
cout << "Enter the mark for CoCurricular res.get(); //read subject marks
Activities: "; cin >> comarks; res.getsm(); //read cocurricular activities
} marks
}; res.display(); //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
Types of Inheritance

Multilevel inheritance
A class is derived from a class that is a
derived class
One class is used as a base class for another
class
class C is derived from Class B. Class B is in turn
derived from Class A.
#include <iostream> class Puppy:public Dog{
#include <string> public:
using namespace std; void weeping()
class Animal {
{ cout<<"Weeps!!";
string name=""; }
public: };
int tail=1; int main()
int legs=4; {
}; Puppy puppy;
class Dog : public Animal cout<<"Puppy has "<<puppy.legs<<"
{ legs"<<endl;
public: cout<<"Puppy has "<<puppy.tail<<"
void voiceAction() tail"<<endl;
{ cout<<"Puppy "; Output:
Puppy has 4 legs
cout<<"Barks!!!"; puppy.voiceAction(); Puppy has 1 tail
} cout<<" Puppy "; Puppy Barks!!!
}; puppy.weeping(); Puppy Weeps!!
Types of Inheritance
Hybrid inheritance
A combination of more than one type of inheritance
For example, a combination of multilevel and multiple
inheritances

we have multiple inheritance (B,


C, and D) and multilevel
inheritance (A, B, and D) to get a
hybrid inheritance.
#include <iostream>
#include <string>
using namespace std;
//Hybrid inheritance = multilevel + multilpe
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(){ int main(){
cout << "Enter sports marks:"; cin >> result
spmarks; res;//object//
}
}; res.getstudent();
class result : public marks, public sports{//Derived class by
multiple inheritance// res.getmarks();
int total_marks;
float avg_marks; res.getsports();
public : res.display();
void display(){ return 0;
}
total_marks=marks_math+marks_phy+marks_chem; Output:
avg_marks=total_marks/3.0; Enter student Id and student
name 25 Ved
cout << "Total marks =" << total_marks << Enter 3 subject marks:89 88 87
endl; Enter sports marks:40
cout << "Average marks =" << avg_marks << Total marks =264
endl; Average marks =88
cout << "Average + Sports marks =" << Average + Sports marks =128
Types of Inheritance
Hierarchical inheritance
Multiple derived classes are created from a single base
class
Multiple classes inherit from a single superclass
#include <iostream>
using namespace std;
//hierarchical inheritance example
class Shape // shape class -> base class
{
public: class Triangle : public Shape // inherit Shape
int x,y; class
{
void get_data(int n,int m) { public:
x= n; int triangle_area() {
y = m; float area = 0.5*x*y;
} return area;
}; }
Shape class
class Rectangle : public Shape // inherit }; classSquare : public Shape // inherit Shape class
{
{ public:
public: int square_area() {
int area_rect() { float area = 4*x;
int area = x*y; return area;
return area; }
} };
};
int main()
{ Rectangle r;
Triangle t;
Square s;
int length,breadth,base,height,side;
//area of a Rectangle
std::cout << "Enter the length and breadth of a rectangle: "; cin>>length>>breadth;
r.get_data(length,breadth);
int rect_area = r.area_rect();
std::cout << "Area of the rectangle = " <<rect_area<< std::endl;
//area of a triangle
std::cout << "Enter the base and height of the triangle: "; cin>>base>>height;
t.get_data(base,height);
float tri_area = t.triangle_area();
std::cout <<"Area of the triangle = " << tri_area<<std::endl;
//area of a Square
std::cout << "Enter the length of one side of the square: "; cin>>side;
s.get_data(side,side); Output:
int sq_area = s.square_area(); Enter the length and breadth of a rectangle: 10
std::cout <<"Area of the square = " << sq_area<<std::endl;
Area of the rectangle = 50
return 0; Enter the base and height of the triangle: 4 8
} Area of the triangle = 16
Enter the length of one side of the square: 5
Area of the square = 20
Inheritance with
Different Access
Specifiers
Understanding Public, Protected, and Private Inheritance in C++
Access Specifiers in Base Class

-public: Accessible outside and in derived


classes
- protected: Accessible only in derived
classes
- private: Not accessible outside or in
derived classes
Inheritance Modes and Effects

Base Class Public Protected Private


Member Inheritanc Inheritanc Inheritanc
e e e
public public protected private
protected protected protected private
private Not Not Not
Accessible Accessible Accessible
Example Code
class Base { class DerivedProtected :
protected Base {
public: int publicVar;
// publicVar becomes
protected: int protectedVar; protected
private: int privateVar; };
};
class DerivedPrivate : private
class DerivedPublic : public Base
{
Base {
// publicVar becomes private
// publicVar remains public };
// protectedVar remains
protected
class DerivedPublic : public Base {
// publicVar remains public
#include <iostream> // protectedVar remains protected
// privateVar is NOT inherited
using namespace std; public:
void show() {
cout << "PublicVar: " << publicVar << endl;
class Base { cout << "ProtectedVar: " << protectedVar <<
public: endl;
// cout << "PrivateVar: " << privateVar; //
int publicVar = 1; ERROR: Not accessible
protected: }
};
int protectedVar = 2;
private: class DerivedProtected : protected Base {
// publicVar becomes protected
int privateVar = 3; // Not // protectedVar remains protected
// privateVar is NOT inherited
inherited public:
}; void show() {
cout << "PublicVar: " << publicVar << endl;
cout << "ProtectedVar: " << protectedVar <<
endl;
}
class DerivedPrivate : private int main() {
Base { DerivedPublic obj1;
// publicVar becomes obj1.show();
cout << obj1.publicVar << endl; //
private
Allowed (public remains public)
// protectedVar becomes
private DerivedProtected obj2;
// privateVar is NOT obj2.show();
inherited // cout << obj2.publicVar; // ERROR:
public: publicVar is now protected
void show() {
DerivedPrivate obj3;
cout << "PublicVar: " << obj3.show();
publicVar << endl; // cout << obj3.publicVar; // ERROR:
cout << "ProtectedVar: " publicVar is now private
<< protectedVar << endl;
} return 0;
}
};
Key Points
- Public Inheritance retains access levels
- Protected Inheritance makes public members
protected
- Private Inheritance makes public and protected
members private
- Private members are never inherited
Inheritance and Constructors in
C++
• When a class is derived from a base class, the
constructors of both classes are executed in a
specific order.
1. Constructor Execution Order
1.Base class constructor runs first.
2.Derived class constructor runs next.
3.If the base class has parameters, the derived
class must explicitly call it.
Types of Constructor
Inheritance
(a) Default Constructor Inheritance
If the base class has a default constructor, it is automatically called
when the derived class object is created.
(b) Parameterized Constructor in Base Class
The derived class must explicitly call the base class constructor.
(c) Constructor Overriding
C++ does not support constructor inheritance directly, but the
derived class can use an initializer list.
(d) Explicit Base Constructor Call
The derived class can call the base class constructor using an
initializer list.
#include <iostream> int main() {
using namespace std; cout << "Creating object d1:\n";
Derived d1; // Calls Base() then Derived()
class Base {
public: cout << "\nCreating object d2:\n";
Base() { cout << "Base class Derived d2(10); // Calls Base(10) then
constructor called\n"; } Derived(10)
Base(int x) { cout << "Base class
parameterized constructor: " << x << return 0;
}
endl; }
};

class Derived : public Base {


public: Creating object d1:
Derived() { cout << "Derived class constructor Base class constructor called
called\n"; } Derived class constructor called
Derived(int x) : Base(x) { // Explicitly calling
Base constructor Creating object d2:
cout << "Derived class parameterized Base class parameterized constructor: 10
constructor: " << x << endl; Derived class parameterized constructor: 10
}
Key Points
•Base class constructor is always executed first.
•Derived class constructor must call a parameterized base
class constructor explicitly.
•C++ does not inherit constructors automatically but allows
derived classes to invoke them.

You might also like