Loading...
C++ Inheritance

C++ Inheritance

In this tutorial, we will learn about Inheritance, Access modes of Inheritance in C++ with the help of examples.

Inheritance

The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important feature of Object Oriented Programming. Inheritance is the capability of one class to acquire properties and characteristics from another class.
Sub Class: The class which inherits properties of other class is called Child or Derived or Sub class. The derived class is the specialized class for the base class.
Super Class:The class whose properties are inherited by other class is called the Parent or Base or Super class.

Inheritance makes the code reusable. When we inherit an existing class, all its methods and fields become available in the new class, hence code is reused.

NOTE:- All members of a class except Private, are inherited.


Purpose of Inheritance in C++

  1. Code Reusability
  2. Method Overriding(Hence, Runtime Polymorphism.
  3. Use of Virtual Keyword

Syntax of Inheritance

class Subclass_name : access_mode base_class_name {
// body of subclass
}; 

Here, subclass_name is the name of the sub class, access_mode is the mode in which you want to inherit this sub class for example: public, private etc. and base_class_name is the name of the base class from which you want to inherit the sub class.

Note: A derived class doesn’t inherit access to private data members. However, it does inherit a full parent object, which contains any private members which that class declares.


Example of Inheritance

Inheritance is one of the key features of Object-oriented programming in C++. It allows us to create a new class (derived class) from an existing class (base class).

The derived class inherits the features from the base class and can have additional features of its own.

class Animal {
    public:
    int legs = 4;
};

// Dog class inheriting Animal class
class Dog : public Animal {
    public:
    int tail = 1;
};

int main() {
    Dog d;
    cout << "Dog have" d.legs "legs."<< endl;
    cout << "Dog have" d.tail "tail."<< endl;
}
Dog have 4 legs.
Dog have 1 tail.

Here, the Dog class is derived from the Animal class. Since Dog is derived from Animal, members of Animal are accessible to Dog.

Notice the use of the keyword public while inheriting Dog from Animal.

class Dog : public Animal {...};

We can also use the keywords private and protected instead of public. We will learn about the differences between using private, public and protected later in this tutorial.


Example 1: C++ Program to find direction using Enumeration

#include <iostream>
using namespace std;

// base class
class Animal {
   public:
    void eat() {
        cout << "I can eat!" << endl;
    }

    void sleep() {
        cout << "I can sleep!" << endl;
    }
};

// derived class
class Cat : public Animal {
   public:
    void meow() {
        cout << "I can meow! Meoww meoww!!" << endl;
    }
};

int main() {
    // Create object of the Cat class
    Cat cat1;

    // Calling members of the base class
    cat1.eat();
    cat1.sleep();

    // Calling member of the derived class
    cat1.meow();

    return 0;
}

Output

I can eat!
I can sleep!
I can meow! meoww meoww!!

Here, cat1 (the object of derived class Cat) can access members of the base class Animal. It's because Cat is inherited from Animal.

// Calling members of the Animal class
cat1.eat();
cat1.sleep();

C++ protected Members

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.

To learn more about protected, refer to our C++ Access Modifiers tutorial.


Example 2: C++ Program to demonstrate protected members

#include <iostream>
#include <string>
using namespace std;

// base class
class Animal {
   private:
    string color;

   protected:
    string type;

   public:
    void eat() {
        cout << "I can eat!" << endl;
    }

    void sleep() {
        cout << "I can sleep!" << endl;
    }

    void setColor(string clr) {
        color = clr;
    }

    string getColor() {
        return color;
    }
};

// derived class
class Cat : public Animal {

   public:
    void setType(string t) {
        type = t;
    }

    void displayInfo(string c) {
        cout << "I am a " << type << endl;
        cout << "My color is " << c << endl;
    }

    void meow() {
        cout << "I can meow! meoww meoww!!" << endl;
    }
};

int main() {
    // Create object of the Cat class
    Cat cat1;

    // Calling members of the base class
    cat1.eat();
    cat1.sleep();
    cat1.setColor("white");

    // Calling member of the derived class
    cat1.meow();
    cat1.setType("mammal");

    // Using getColor() of cat1 as argument
    // getColor() returns string data
    cat1.displayInfo(cat1.getColor());

    return 0;
}

Output

I can eat!
I can sleep!
I can meow! meoww meoww!!
I am a mammal
My color is white

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

On the other hand, the private variable color cannot be initialized in Cat.

class Cat : public Animal {
                                                                      
    public:
      void setColor(string clr) {
          // Error: member "Animal::color" is inaccessible
          color = clr; 
      }
};

Also, since the protected keyword hides data, we cannot access type directly from an object of Cat or Animal class.

// Error: member "Animal::type" is inaccessible
cat1.type = "mammal";

C++ Access Modes of Inheritance

In our previous tutorials, we have learned about C++ access specifiers such as public, private, and protected.
So far, we have used the public keyword in order to inherit a class from a previously-existing base class. However, we can also use the private and protected keywords to inherit classes.

For example,

class Animal {
    // code
};

class Dog : private Animal {
    // code
};

class Cat : protected Animal {
    // code
};

The various ways we can derive classes are known as access modes. These access modes have the following effect:

  1. Public mode: This is the most used inheritance mode. In this the protected member of super class becomes protected members of sub class and public becomes public.
  2. Protected mode: In protected mode, Then both public member and protected members of the Super class will become protected in Sub class.
  3. Private mode: In private mode, the protected and public members of super class become private members of Sub class.

The private members of the base class are always private in the derived class.


Table showing all the Visibility Modes

Derived Class Derived Class Derived Class
Base class Public Mode Private Mode Protected Mode
Private Not Inherited Not Inherited Not Inherited
Protected Protected Private Protected
Public Public Private Protected

To learn more, visit our C++ public, private, protected inheritance tutorial.


Member Function Overriding in Inheritance

Suppose, base class and derived class have member functions with the same name and arguments.

If we create an object of the derived class and try to access that member function, the member function in the derived class is invoked instead of the one in the base class.

The member function of derived class overrides the member function of base class.

Learn more about Function overriding in C++.

Recommended Reading: C++ Multiple Inheritance



Next Tutorial

We hope that this tutorial helped you develop better understanding of the concept of Inheritance in C++.

Keep Learning : )

In the next tutorial, you'll learn about C++ Inheritance Access Control.

- Related Topics