×

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

Containership in C++

In C++, it is possible to create an object in one class into another class, and that object is a member of another class. This relationship is known as a...

4 minutes read.

How to create a button in C++

A button is an option through which a user can control to click a provided input to an application. There are several buttons, each with different styles, to maintain the...

3 minutes read.

Array program in C++

What is an Array? An array is a set of identically typed elements that are organized into contiguous memory locations and each element can be independently accessed using an index. We can...

16 minutes read.

Const_cast in C++ Type Casting Operators

In this tutorial, we will learn enough about const cast in the most widely used programming language, C++, as well as type casting operations. C++ supports the four types of casting...

4 minutes read.

C++ Output 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...

4 minutes read.

C++ | C Plus Plus While loop

In this article, we will discuss the C++ while loop with its syntax, use, key features, key points, pseudo code, and examples. What is the While Loop? The “while loop” is a...

4 minutes read.

Stringstream in C++ and its applications

In this tutorial, we will explore what the stringstream in C++ is. We will also learn its application. What is stringstream? With the aid of a stringstream, user can read from a...

2 minutes read.

Types of polymorphism in C++

What is polymorphism in C++ ? Polymorphism literally translates to "multiple forms". This indicates that the same thing behaves differently depending on the context in programming. Polymorphism is a feature of C++...

6 minutes read.

Object in C++

In this article, we will learn about Object in C++. In short, an object is a stateful entity with behaviour. Data is referred to as state, and functionality is referred to...

3 minutes read.

Include Guards in C++

In C++ programming, we frequently utilize a class more than once, so it is necessary to create a header file and include it in the main program. Now, occasionally a...

3 minutes read.

C++ Call by Reference

Call by Reference is a C++ method for passing arguments to a function that enables us to pass the actual memory address of the parameter rather than a copy of...

4 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.

Copy elision in C++

The Copy Omission is another name for the Copy Elision. One of the several compiler optimization techniques is copy elision. It prevents items from being copied inadvertently. This Copy Elision approach...

3 minutes read.

Destructor

Let’s discover the C++ destructor, virtual and pure virtual destructors, and when destructors are invoked and their rules in this lesson. Destructors : A member function that destroys an object is known as...

5 minutes read.

Palindrome Number Program in C++

A palindrome number is one that is the same when it is reversed. Palindrome numbers include 22, 33, 44, 55, 66, 77, 88, and 99. Algorithm for Palindrome Numbers Get the user's...

4 minutes read.

Dynamic Memory Allocation in C++

In some programming situations, the number of data items changes as the program is running, which is known as dynamic data or input. Consider a real-world situation where a program...

3 minutes read.

Constructor Overloading in C++

A Constructor is a class member function that is used to initialize the class's objects. Constructors have no return type and are called automatically when an object is formed. Constructor Characteristics Constructors...

3 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.

C++ Interfaces

The C++ programming language provides programmers with a variety of capabilities and functions. It also enables object-oriented programming, which is essential while working on a project. It will be simple...

7 minutes read.

Auto keyword in C++

The primary function of auto keyword is to assign and detect the value of the data type automatically in C++. The compiler knows the data type of the variable by...

2 minutes read.