Inheritance
Inheritance
1
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.
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.
The idea of inheritance implements the “is a relationship”. For example, mammal IS-A animal,
dog IS-A mammal hence dog IS-A animal as well and so on.
2
Types of Inheritance
Single Inheritance
Inheritance
Multiple
Inheritance
Multilevel
Inheritance
Hierarchical
Inheritance
Hybrid Inheritance
3
Types of Inheritance
4
Single Inheritance
If a single class is derived from one base class then it is called single inheritance.
5
Syntax
class derived-class: access-specifier base-class
6
Example
#include <iostream> int main() {
using namespace std;
// Create an object of the derived class
class Animal { //Base Class
Dog myDog;
public:
void eat() { // Access the member functions of the base class
cout << "Animal is eating." << endl; } myDog.eat();
}; // Access the member functions of the derived
class Dog : public Animal { // Derived class class
public: myDog.bark();
void bark() {
return 0;
cout << "Dog is barking." << endl; }
}
};
7
Explanation
• The Animal class is the base class, which has a member function eat().
• The Dog class is the derived class, which inherits publicly from the Animal class.
• The Dog class adds its own member function bark().
• In the main() function, an object myDog of the Dog class is created.
• The object myDog can access both the base class function eat() and the derived class function
bark().
8
Access Specifier
Access Specifier may be public, protected or private.
In a public class, functions are accessible within all other classes.
The functions defined within a private class are only accessible within the same class.
In a protected class, on the other hand, access from outside the class is denied but allowed in
derived classes.
9
Order of Constructor &
Destructor
10
Destructors
Destructor is also a special member function like constructor. Destructor destroys the class
objects created by constructor.
Destructor has the same name as their class name preceded by a tilde (~) symbol.
It is not possible to define more than one destructor.
The destructor is only one way to destroy the object create by constructor. Hence destructor
can-not be overloaded.
Destructor neither requires any argument nor returns any value.
It is automatically called when object goes out of scope.
Destructor release memory space occupied by the objects created by constructor.
In destructor, objects are destroyed in the reverse of an object creation.
11