×

Use of Inheritance in C++

What is inheritance in c++?

Inheritance is fundamental in object-oriented programming (OOP) languages like C++. It allows a programmer to create a new class (called a derived class) that inherits the properties and behaviors of an existing class (called a base class). This enables the programmer to reuse existing code and avoid duplication, which can save time and improve the reliability of their programs.

In C++, inheritance is implemented using the: operator, followed by the access specifier (such as public) and the name of the base class.

Here is an example of how inheritance might be used in C++:

#include <iostream>


// Base class (Animal)
class Animal
{
  public:
    void move()
    {
      std::cout << "The animal is moving" << std::endl;
    }
};


// Derived class (Dog)
class Dog: public Animal
{
  public:
    void bark()
    {
      std::cout << "Woof!" << std::endl;
    }
};


int main()
{
  // Create a dog object
  Dog dog;


  // Use the move() method from the Animal class
  dog.move();


  // Use the bark() method from the Dog class
  dog.bark();


  return 0;
}

Output:

Use of Inheritance in C++

Explanation:

The above code is used to demonstrate inheritance. In this program, the "Dog" class is derived from the "Animal" class and has access to its move() method. In the main() function, a "Dog" object is created, and the move() and bark() methods are called.

One of the key benefits of inheritance is code reuse. By creating a hierarchy of classes, a programmer can define common properties and behaviors in a base class and then reuse them in derived classes. This can save time and improve the program's reliability because the programmer does not have to rewrite the same code multiple times.

Here is a simple C++ program that demonstrates how inheritance can be used for code reuse:

#include <iostream>


// Base class (Animal)
class Animal
{
  public:
    void move()
    {
      std::cout << "The animal is moving" << std::endl;
    }
};


// Derived class (Dog)
class Dog: public Animal
{
  public:
    void bark()
    {
      std::cout << "Woof!" << std::endl;
    }
};


// Derived class (Cat)
class Cat: public Animal
{
  public:
    void meow()
    {
      std::cout << "Meow!" << std::endl;
    }
};


int main()
{
  // Create a dog object
  Dog dog;


  // Use the move() method from the Animal class
  dog.move();


  // Use the bark() method from the Dog class
  dog.bark();


  // Create a cat object
  Cat cat;


  // Use the move() method from the Animal class
  cat.move();


  // Use the meow() method from the Cat class
  cat.meow();


  return 0;
}

Output:

Use of Inheritance in C++

Explanation:

In this program, the "Animal" class defines a move() method, and the "Dog" and "Cat" classes are derived from the "Animal" class. This means that the "Dog" and "Cat" classes can use the move() method without having to provide their implementation.

In the main() function, "Dog" and "Cat" objects are created, and the move() and bark()/meow() methods are called.

This demonstrates how inheritance allows derived classes to reuse the functionality of their base class and provide their unique behavior. It also shows how a base class can provide a common interface for derived classes so that code can be written that can be used with objects of different types without knowing the specific type at compile time.

Another key benefit of inheritance is polymorphism, which allows derived classes to provide their own implementations of base class methods. This is achieved through the use of virtual methods and the override keyword.

Virtual methods are declared using the virtual keyword in the base class and the override keyword in the derived class. This tells the compiler that the derived class method is intended to override the base class method. Here is a simple C++ program that demonstrates the use of virtual methods and the override keyword:

#include <iostream>


// Base class (Shape)
class Shape
{
  public:
    // Virtual method for calculating the area
    virtual double getArea() = 0;
};


// Derived class (Circle)
class Circle: public Shape
{
  public:
    Circle(double radius)
    {
      this->radius = radius;
    }


    double getArea() override
    {
      return 3.14159 * radius * radius;
    }


  private:
    double radius;
};


int main()
{
  // Create a circle object with radius 5
  Circle circle(5);


  // Use the getArea() method to calculate the circle's area
  std::cout << "Area: " << circle.getArea() << std::endl;


  return 0;
}

Output:

Use of Inheritance in C++

Explanation:

In this program, the "Shape" class defines a virtual method called getArea() that calculates the area of a shape. The "Circle" class is derived from the "Shape" class and provides its implementation of the getArea() method, which calculates the area of a circle based on its radius.

The getArea() method in the "Shape" class is declared as virtual and the getArea() method in the "Circle" class is declared with the `over


Related Topics

C++ For loop

C++ loop Statement C++ Loop statement allows us to repeat the execution of a statement or group of statements multiple times. The statement(s) repeat execution within loop until the condition of loop...

2 minutes read.

gmtime() function in C/C++

C++ language is used to make high-performance applications that can work efficiently. It is one of the world's most popular languages. It is an object-oriented and high-level programming language, which...

4 minutes read.

Initialization of Data Members

In this tutorial, we'll look at how to initialise static member variables in C++. Static members, such as functions or variables, can be added to C++ classes. After declaring the...

1 minute read.

Decltype type Specifier in C++

The primary use of C++ decltype is to inspect the declaration type of an entity in an expression. The auto keyword can declare a particular type of variable, whereas the...

4 minutes read.

C++ Forward Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

Input Iterators in C++

What are input iterators? Input iterators are used in sequence for carrying out input operations where each value is read-only. It is pointed by the iterator and further incremented. All the iterators...

4 minutes read.

4 Pillars of OOPs

OOPs OOPS means Object Oriented Programming System Structure. Object oriented Programming is defined as an approach that provides a way of modularizing programs by creating partitioned memory area for both data...

11 minutes read.

C++ References

C++ References An alias is a reference variable that is another name for a variable already in existence. If a relation is initialized with a variable, it is possible to use...

3 minutes read.

How to create a library in C++

Before going on to the creation of a library, let’s understand its meaning. What is a library? In simple words, a library is a collection of numerous functions, methods, classes, header files...

7 minutes read.

Function overloading in C++

Function overloading in C++ As we know that C++ works on the OOP Concepts, that are abstraction, encapsulation, and data hiding, it also uses the other important feature of OOP, which...

8 minutes read.

C++ Try-Catch

Every useful program will eventually encounter unexpected outcomes. By entering data that are incorrect, users might create mistakes. Sometimes the program's creator didn't consider all of the options or was...

7 minutes read.

Design Patterns in C++

A design pattern offers an all-encompassing, repeatable answer to the typical issues that arise in software design. Usually, the pattern demonstrates the connections and interactions between several classes or objects....

10 minutes read.

Top 5 IDEs for C++ That You Should Try Once

In the past decades, creating an application or interface from the very basic idea, the developer has to struggle a lot for it. Because an application is a combination of...

3 minutes read.

C++ Overriding

C++ Function Overriding When the base and derive class both contain the same function name and calling the function through derived object invokes derived class function called function overriding. Function overloading is...

1 minute read.

How to initialize a dynamic array in C++

Regular arrays or static arrays have a predetermined size or fixed size. Change in the size of regular arrays is not possible. The memory size for static arrays determines at compile...

4 minutes read.

C++ Ternary Operator

In this tutorial, we'll learn about the C++ ternary operator and how to utilise it to manage the program's flow using examples. Ternary Operator: The if-else statement and the conditional operator use...

3 minutes read.

ATM machine program in C++ using functions

Automated Teller Machines (ATMs) carry out daily financial transactions. They are straightforward and simple, allowing customers to complete self-service transactions quickly. ATMs can then be used to withdraw cash, deposit...

3 minutes read.

std::min in C++

std::min in C++ std::min is specified in the program code, used to calculate the lowest amount that has been transferred. When there's more of someone who returns first of them. It's used...

2 minutes read.

Processing strings using std string stream in C++

A string class object called std: string stream is used to streamline into various variables, just as files can pour into strings. This class's things make use of a string...

3 minutes read.

Hierarchical Inheritance

C++ Hierarchical Inheritance Hierarchical inheritance inherits the property of one base class in more than one derived class.   C++ Hierarchical Inheritance Example #include <iostream>   using namespace std;   class Person {       char gender[10];       int age;   public:       void getPerson()       {           cout << "Age: "; cin >> age;           cout << "Gender: "; cin >> gender;       }       void dispPerson()       {           cout << "Age: " << age << endl;           cout << "Gender: " << gender << endl;       }   };   class Employee : public Person {       float salary;   public:       void getEmployee()       {           Person::getPerson();           cout << "Salary: Rs."; cin >> salary;       }       void dispEmployee()       {           Person::dispPerson();           cout << "Salary: Rs." << salary << endl;       }   };   class Student : public Person {       char level[20];   public:       void getStudent()       {           Person::getPerson();           cout << "Class: "; cin >> level;       }       void dispStudent()       {           Person::dispPerson();           cout << "Level: " << level << endl;       }   };   int main()   {       Person per;       Employee emp;       Student stu;       cout << "Student data" << endl;       cout << "Enter data" << endl;       stu.getStudent();       cout << endl << "Displaying data" << endl;       stu.dispPerson();       cout << endl << "Staff Data" << endl;       cout << "Enter data" << endl;       emp.getEmployee();       cout << endl << "Displaying data" << endl;       emp.dispPerson();   } Output: Student data Enter data Age: 10 Gender: f Class: 5 Displaying data Age: 10 Gender: f Employee data Enter data Age:...

1 minute read.