What is the meaning of inheritance in C++. Write an example of simple 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. 
  For example,

class Animal {
    // eat() function
    // sleep() function
};

class Dog : public Animal {
    // bark() function
};
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

Example:
// C++ program to demonstrate inheritance

#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 Dog : public Animal {
 
   public:
    void bark() {
        cout << "I can bark! Woof woof!!" << endl;
    }
};

int main() {
    // Create object of the Dog class
    Dog dog1;

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

    // Calling member of the derived class
    dog1.bark();

    return 0;
}
Output

I can eat!
I can sleep!
I can bark! Woof woof!!
Here, dog1 (the object of derived class Dog) can access members of the base class Animal.
It's because Dog is inherited from Animal.

Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source