Upskill faster and boost your growth in 2024 with our upto 50% OFF on All Courses! Offer Ending in
D
H
M
S
Get Now
Browse Articles
Inheritance in C++ with Modifiers

Inheritance in C++ with Modifiers

05 Dec 2023
Advanced
2.67K Views
11 min read
Learn via Video Course & by Doing Hands-on Labs

C++ Programming Course

Start Learning View All Courses

Inheritance in C++: An Overview

Understanding inheritance is essential if want to improve your programming abilities in C++. We'll be taking an in-depth look at this particular topic today in this C++ tutorial - so settle down with us as we discuss this important concept. For more check our C++ Certification Training program.

What is Inheritance in C++?

Inheritance is a basic object-oriented programming (OOP) concept in C++ that allows one class to inherit the attributes and functions of another. This means that the derived class can use all of the base class's members as well as add its own. Because it reduces the need to duplicate code for comparable classes, inheritance promotes code reusability and maintainability.

What is Inheritance in C++

Example of Inheritance in C++

        #include <iostream>
class Animal {
public:
  void eat() {
    std::cout << "Animal is eating." << std::endl;
  }
};
class Dog : public Animal {
public:
  void bark() {
    std::cout << "Dog is barking." << std::endl;
  }
};
int main() {
  Dog dog;
  dog.eat(); // Animal is eating.
  dog.bark(); // Dog is barking.
  return 0;
}

The Dog class in this example derives from the Animal class. This means that the Dog class includes all of the members of the Animal class, as well as any extra members defined by it. The Dog class defines an additional member method called bark() in this situation.The main() function creates a Dog class object and calls its eat() and bark() member functions.

Output

        Animal is eating.Dog is barking.

Why use inheritance in C++?

  • By allowing you to inherit common members from a base class into derived classes, inheritance increases code reusability.
  • This eliminates the need for duplicating code and reduces the total coding effort.
  • Inheritance aids in the hierarchical organization of code by reflecting the links between various classes.
  • This improves the readability and maintainability of the code.
  • Inheritance is the foundation for polymorphism, allowing objects of different classes to respond to the same method calls in different ways.
  • This increases C++ object-oriented program flexibility and extension.

When to use inheritance in C++

  • When you have a class hierarchy: If you have a group of related classes, and there is a considerable amount of code that is shared by all of them, then inheritance is an acceptable option.
  • When you want to construct polymorphic classes: Inheritance is an excellent choice if you want to create classes that can respond to the same message in multiple ways.
  • When you need to organize your code: If you wish to organize your code more logically and understandably, inheritance might be a useful concept.

Types of Inheritance Classes:

There are two types of Inheritance Classes in C++:
  1. Base Class
  2. Derived Class

1. Derived Class

A derived class inherits the base class's properties and methods. The derived class can inherit all of the base class's attributes and methods or only a subset of them. The derived class may additionally include its own set of properties and methods.

2. Base Class

A base class is one that other classes inherit from. The base class defines the attributes and methods that its derived classes inherit. In addition, the base class can specify its properties and methods.

Example of Inheritance Classes

        
#include <iostream>
class Shape {
public:
 virtual void draw() = 0;
};
class Circle : public Shape {
public:
 Circle(int radius) : radius(radius) {}
 void draw() override {
  std::cout << "Drawing a circle with radius " << radius << std::endl;
 }
private:
 int radius;
};
class Rectangle : public Shape {
public:
 Rectangle(int width, int height) : width(width), height(height) {}
 void draw() override {
  std::cout << "Drawing a rectangle with width " << width << " and height " << height << std::endl;
 }
private:
 int width;
 int height;
};
int main() {
 Circle circle(5);
 Rectangle rectangle(10, 20);
 circle.draw();
 rectangle.draw();
 return 0;
}
This example demonstrates inheritance in C++ by creating a base class called Shape and two derived classes, Circle and Rectangle. The Shape class defines a pure virtual function called draw(), which forces derived classes to provide their implementation of the function. Both the Circle and Rectangle classes implement the draw() function to draw their respective shapes. The main() function creates instances of Circle and Rectangle and calls their draw() functions to display the shapes.

Output

Drawing a circle with radius 5

Drawing a rectangle with width 10 and height 20

Access Modes of Inheritance

There are three Access Modes of Inheritance in C++:

1. Public Mode

When we derive a subclass from a public base class. Then the base class's public members become public in the derived class, and the base class's protected members become protected in the derived class.

2. Protected Mode

When a subclass is derived from a Protected base class. Then, in the derived class, both public and protected members of the base class will be protected.

3. Private Mode

When a subclass is derived from a Private base class. The base class's public and protected members will then become Private in the derived class.

C++ protected Members

  • Protected members are a sort of access specifier in C++ that regulates the accessibility of class members.
  • Protected members can be accessed from within the class, as well as from any derived classes and friend functions in C++.
  • They are, however, inaccessible from outside the class or from any other classes that are not inherited from it.

Here is a table summarising protected members' accessibility:

Access LevelAccess
Inside the classYes
Derived classesYes
Friend functionsYes
Outside the classNo
Other classesNo

Example of C++ Protected Members

        
#include <iostream>
class Base {
protected:
 int data;
public:
 Base(int data) {
  this->data = data;
 }
 int getData() {
  return data;
 }
};
class Derived : public Base {
public:
 Derived(int data) : Base(data) {}
 int getDerivedData() {
  return data * 2;
 }
};
int main() {
 Base base(10);
 Derived derived(20);
 // Output: 10
 std::cout << base.getData() << std::endl;
 // Output: 20
 std::cout << derived.getData() << std::endl;
 // Output: 40
 std::cout << derived.getDerivedData() << std::endl;
 return 0;
}

In this example, the Base class's data member is protected, limiting access to the Base class, its derived classes, and friend methods of the Base class. The data member is unreachable outside of these bounds. The Derived class receives access to the data member by inheriting from the Base class, allowing the getDerivedData() method to access and alter it. This demonstrates how protected members can be accessed in a controlled manner within class hierarchies.

Output

102040

Types of Inheritance in C++

C++ supports five main Types of Inheritance in C++:
  1. Single Inheritance: A single inheritance occurs when a class inherits from only one parent class.
  2. Multiple Inheritance: Multiple Inheritance occurs when a class inherits from two or more parent classes.
  3. Multilevel inheritance: Multilevel inheritance occurs when one class inherits from another, which in turn inherits from another, and so on.
  4. Hierarchical Inheritance: Multiple classes inherit from a single-parent class in a hierarchical inheritance.
  5. Hybrid Inheritance: Multiple inheritance and multilevel inheritance are combined in hybrid inheritance.
Summary

Learning about inheritanceC++ programming can help you better understand how objects are related to one another. This can be a helpful tool when working with large programs. If you want to learn more about inheritance in C++ programming, you can go for C++Certification and you will get a vast idea about inheritance.

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this