0% found this document useful (0 votes)
46 views28 pages

Lecture 6 - Inheritance

Inheritance allows a class to inherit properties from another class. The existing class is called the base class, and the new class is the derived class. Inheritance provides code reuse and faster development time. A derived class inherits the data members and member functions of the base class. Virtual functions allow overriding base class functions in derived classes and ensure the correct version is called based on the object type.

Uploaded by

adibsadman10
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)
46 views28 pages

Lecture 6 - Inheritance

Inheritance allows a class to inherit properties from another class. The existing class is called the base class, and the new class is the derived class. Inheritance provides code reuse and faster development time. A derived class inherits the data members and member functions of the base class. Virtual functions allow overriding base class functions in derived classes and ensure the correct version is called based on the object type.

Uploaded by

adibsadman10
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
You are on page 1/ 28

Inheritance in C++

Mousumi Hasan,
Assistant Professor, Department of CSE, BAIUST
Example: Insect Taxonomy

2
C++ Inheritance
One of the most important concepts in object-oriented
programming is that of inheritance. Inheritance allows us
to define a class in terms of another class, which makes it
easier to create and maintain an application. This also
provides an opportunity to reuse the code functionality and
fast implementation time.

When creating a class, instead of writing completely new


data members and member functions, the programmer
can designate that the new class should inherit the
members of an existing class. This existing class is called
the base class, and the new class is referred to as
the derived class.
Inheritance

► The language mechanism by which one class acquires the properties (data and
operations) of another class
► Base Class (or superclass): the class being inherited from
► Derived Class (or subclass): the class that inherits
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
The "is a" Relationship

• Inheritance establishes an "is a" relationship between classes.


– A poodle is a dog
– A car is a vehicle
– A flower is a plant
– A football player is an athlete

6
Inheritance – Terminology and Notation
in C++ Base class (or parent) – inherited from

► Derived class (or child) – inherits from the base class
► Notation:
class Student // base class
{
. . .
};
class UnderGrad : public student
{ // derived class
. . .
};

7
Back to the ‘is a’ Relationship

► An object of a derived class 'is a(n)' object of the base class


► Example:
► an UnderGrad is a Student
► a Mammal is an Animal
► A derived object has all of the characteristics of the base class

CS1 -- Inheritance and Polymorphism 8


C++ Protected Access Specifier
The access modifier protected is especially relevant when it
comes to C++ inheritance.

Like private members, protected members are inaccessible


outside of the class. However, they can be accessed by
derived classes and friend classes/functions.

We need protected members if we want to hide the data of a


class, but still want that data to be inherited by its derived
classes.
C++ Protected Access Specifier

Here, the variable type is


protected and is thus accessible
from the derived class Dog. We
can see this as we have initialized
type in the Dog class using the
function setType().

On the other hand, the private


variable color cannot be initialized
in Dog.
Types of Inheritance
1. Single class Inheritance:

Single inheritance is the one where you have a


single base class and a single derived class.

Class Employee It is a Base class (super)

Class Manager it is a sub class (derived)


#include <iostream>
using namespace std;
class base //single base class int main()
{ {
public: derive a; //object of derived class
int x; a.getdata();
void getdata() a.readdata();
{ a.product();
cout << "Enter the value of x = "; cin >> x; return 0;
} }
};
class derive : public base //single derived class
{
private:
int y;
public: OUTPUT:
void readdata() Enter the value of x = 3
{ Enter the value of y = 4
cout << "Enter the value of y = "; cin >> y; Product = 12
}
void product()
{
cout << "Product = " << x * y;
} };
Types of Inheritance
2. Multilevel Inheritance:
In Multi level inheritance, a class inherits its
properties from another derived class.

Class A it is a Base class (super) of B

Class B it is a sub class (derived) of A


and base class of class C

Class C derived class(sub) of class B


// Base class (parent)
class MyClass {
public:
void myFunction() {
cout << "Some content in parent class." ;
}
};

// Derived class (child)


class MyChild: public MyClass {
//some operation
};

// Derived class (grandchild)


class MyGrandChild: public MyChild {
//some operation
};

int main() {
MyGrandChild myObj;
myObj.myFunction();
return 0;
}
Types of Inheritance
3. Multiple Inheritances:

In Multiple inheritances, a derived class inherits


from multiple base classes. It has properties of both
the base classes.

Class A Class B Base class

Class C Derived class


#include <iostream>
using namespace std;

class Mammal {
public:
Mammal() {
cout << "Mammals can give direct birth." << endl;
}
};

class WingedAnimal {
public:
WingedAnimal() {
cout << "Winged animal can flap." << endl;
}
};

class Bat: public Mammal, public WingedAnimal {};

int main() {
Bat b1;
return 0;
}
Types of Inheritance
4. Hierarchical Inheritance:

In hierarchical Inheritance, it's like an inverted tree.


So multiple classes inherit from a single base class.
It's quite analogous to the File system in a unix
based system.

Class A

Class B Class D Class C


#include <iostream>
Function Overriding
// Base class
class Shape {
public: int main() {
void draw() { // Create objects of the derived classes
std::cout << "Drawing a generic shape." << Rectangle rectangle;
std::endl; Circle circle;
}
}; // Call the draw() function of the objects
// Derived class Rectangle inheriting from Shape rectangle.draw(); // Output: "Drawing a rectangle."
class Rectangle : public Shape { circle.draw(); // Output: "Drawing a circle."
public:
void draw() { // Call the draw() function of the base class through
std::cout << "Drawing a rectangle." << std::endl; the derived class objects
} rectangle.Shape::draw(); // Output: "Drawing a
}; generic shape."
// Derived class Circle inheriting from Shape circle.Shape::draw(); // Output: "Drawing a generic
class Circle : public Shape { shape."
public:
void draw() { return 0;
std::cout << "Drawing a circle." << std::endl; }
}
};
Function Overriding

► Function overriding is a concept in C++ that allows a derived class to provide


a specific implementation for a method that is already defined in its base
class. When a function is overridden in the derived class, the derived class's
version of the function takes precedence over the base class's version when
called through a derived class object.
► To achieve function overriding, the base class function must be declared as
virtual, and the derived class function must have the same function signature
(name, return type, and parameters) as the base class function.
Types of Inheritance
5. Hybrid Inheritance:
✔In this type of inheritance, we can have mixture of
number of inheritances but this can generate an
error of using same name function from no of
classes, which will bother the compiler to how to
use the functions.
✔Therefore, it will generate errors in the program.
This has known as ambiguity or duplicity.
✔Ambiguity problem can be solved by using virtual
base classes
Types of Inheritance
5. Hybrid Inheritance:

Class A

Class B Class C

Class D
Virtual Functions
► A virtual function (also known as virtual methods) is a member function that is declared within a base
class and is re-defined (overridden) by a derived class. When you refer to a derived class object using
a pointer or a reference to the base class, you can call a virtual function for that object and execute
the derived class’s version of the method.
► Virtual functions ensure that the correct function is called for an object, regardless of the type of
reference (or pointer) used for the function call.
► They are mainly used to achieve Runtime polymorphism.
► Functions are declared with a virtual keyword in a base class.
► The resolving of a function call is done at runtime.
Rules for Virtual Functions
► The rules for the virtual functions in C++ are as follows:
► Virtual functions cannot be static.
► A virtual function can be a friend function of another class.
► Virtual functions should be accessed using a pointer or reference of base class type to
achieve runtime polymorphism.
► The prototype of virtual functions should be the same in the base as well as the derived
class.
► They are always defined in the base class and overridden in a derived class. It is not
mandatory for the derived class to override (or re-define the virtual function), in that
case, the base class version of the function is used.
► A class may have a virtual destructor but it cannot have a virtual constructor.
#include <iostream>
using namespace std;

class base {
public:
virtual void print() { cout << "print base class\n"; }

void show() { cout << "show base class\n"; }


};

class derived : public base {


public:
void print() { cout << "print derived class\n"; }

void show() { cout << "show derived class\n"; }


};
int main()
{
base* bptr;
derived d;
bptr = &d;

// Virtual function, binded at runtime


bptr->print();

// Non-virtual function, binded at compile time


bptr->show();

return 0;
}

print derived class


show base class
// C++ program to illustrate
// working of Virtual Functions
#include <iostream>
using namespace std;

class base {
public:
void fun_1() { cout << "base-1\n"; }
virtual void fun_2() { cout << "base-2\n"; }
virtual void fun_3() { cout << "base-3\n"; }
virtual void fun_4() { cout << "base-4\n"; }
};

class derived : public base {


public:
void fun_1() { cout << "derived-1\n"; }
void fun_2() { cout << "derived-2\n"; }
void fun_4(int x) { cout << "derived-4\n"; }
};
int main()
{
base* p;
derived obj1;
p = &obj1;

// Early binding because fun1() is non-virtual


// in base Output:
p->fun_1(); base-1
derived-2
// Late binding (RTP)
base-3
p->fun_2();
base-4
// Late binding (RTP)
p->fun_3();

// Late binding (RTP)


p->fun_4();

// Early binding but this function call is


// illegal (produces error) because pointer
// is of base type and function is of
// derived class
// p->fun_4(5);
Thank You!!!

You might also like