Inheritance in C++

Inheritance in C++

Inheritance in C++ allows us to define a class in terms of another class, which makes it easier to create and maintain an application. 

Inheritance also provides an opportunity to use again the code functionality and fast implementation time.

When creating a class, instead of writing completely new data members and member functions, the programmer can designate that a new class should inherit the members of an existing class. 

 

Syntax of Inheritance

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

Inheritance allows us to create a new class called a derived class from an existing class called a base class.

The derived class inherits the from the base class.

 

Example of Inheritance

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;
}

Output

Dog have 4 legs.
Dog have 1 tail.

 

Program of Inheritance in C++

#include <iostream>
using namespace std;

// base class
class Animal {

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

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

// derived class
class Dog : public Animal {
 
   public:
    void bark() {
        cout << "Animal can bark" << endl;
    }
};

int main() {
    Dog dog1;
    dog1.eat();
    dog1.sleep();

 
    dog1.bark();

    return 0;
}

Output

Animal can eat
Animal can sleep
Animal can bark

 

 

Read more, Inheritance in C++

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *