Page 304 - Computer_Science_F5
P. 304

Inheritance in C++

              The following Program Example 4.42 demonstrate how inheritance is implemented.

                       Program Example 4.42:                                                       Chapter Four: Object oriented programming with C++
          FOR ONLINE READING ONLY
               Program code demonstrating inheritance

                 #include <iostream>
                 using namespace std;
                 // Parent class
                 class Animal {
                 public:
                     void eat() {
                         cout << “The animal of this class will eat: mnyaa! mnyaa!mnyaa!” << endl;
                     }
                     void sleep() {
                         cout << “The animal of this class will sleep” << endl;
                     }
                 };
                 // Child class
                 class Dog : public Animal {
                 public:
                     void bark() {
                         cout << “The Dog will bark: wo!wo!wo!” << endl;
                     }
                 };
                 int main() {
                     // This will create an object of the child class
                     Dog thisDog;
                     // This will call methods from the parent class
                     thisDog.eat();
                     thisDog.sleep();
                     // This will call method from the child class
                     thisDog.bark();
                     return 0;
                 }


                Output:







                                    Figure 4.71: Output of inheritance program


                                                    295
               Student’s Book  Form Five



     Computer Science Form 5.indd   295                                                     23/07/2024   12:34
   299   300   301   302   303   304   305   306   307   308   309