Inheritance is to reuse the Behaviors/methods and properties/state of a Parent class in child class.
So, he created LivingBeing class.
class LivingBeing { public: void breathe() { cout << "Breathes oxygen from air."; } };
Now, LivingBeing is the parent class and Human class is going to be the child class.
Let us see in the below example.
#include <iostream> using namespace std; class LivingBeing { public: void breathe() { cout << "Breathes oxygen from air."; } }; class Human : public LivingBeing { private : string name; string food; string language; public : Human() { } Human(string nme, string fd, string lang) { name = nme; food = fd; language = lang; } void eat() { cout << name << " eats " << food << endl; } void speak() { cout << name << " speaks " << language << endl; } }; int main() { Human human1("John", "Burger", "English"); human1.eat(); human1.speak(); human1.breathe(); return 0; }
So, in the above example, we have created a LivingBeing class that just has a Behaviour/Function i.e. breathe().
class LivingBeing { public: void breathe() { cout << "Breathes oxygen from air."; } };
Then we have created the Human class and the Human class should have the breathe() method from the LivingBeing class.
And since, the breathe() method is defined in the LivingBeing class. There is no point in redefining the breathe() method again.
Rather the Human class reuses it by inheriting all the members of the LivingBeing class.
class Human : public LivingBeing
The syntax is quite simple. We just place the class to be inherited(i.e. LivingBeing) followed by colon(i.e. :).
And what happens is, breathe() method of LivingBeing class becomes a part of the Humanclass.
And along with eat() and speak() method, breathe() method also becomes a part of Human class.
Now, after creating the human1 object,
Human human1("John", "Burger", "English";
Now when we call the breathe() method from human1 object.
human1.breathe()
We get the below output.
Breathes oxygen from air