Page 305 - Computer_Science_F5
P. 305

Computer Science  In the code above, the parent class is called Animal and it has two methods: eat()
           and sleep().

           The child class, Dog, is created based on the Animal class. It inherits the methods
           from Animal and adds a new method called bark(). In the main() function, an object
          FOR ONLINE READING ONLY
           of type Dog is created. This object can access and call methods from both the parent
           class (Animal) and the child class (Dog).



               Activity 4.10:

             Developing program to deposit and withdraw money
            Assume you have been hired by a bank to develop a program for customers to
            deposit and withdraw money. The program should check if the requested withdrawal
            amount exceeds the current balance before processing. It should also perform
            additional functions


           Polymorphism in C++

           This example shows how to implement polymorphism.

                    Program Example: 4.43:

            Program code demonstrating polymorphism


                #include <iostream>
                using namespace std;
                // Parent class
                class Shape {
                public:
                    // This code shows Virtual function
                    virtual void draw() {
                        cout << “The drawn shape is expected here” << endl;
                    }
                };
                // Child class Circle
                class Circle : public Shape {
                public:
                    // This code will override the draw() method
                    void draw() override {
                        cout << “The drawn Circle is expected here” << endl;
                    }


                                                 296
                                                                for Advanced Secondary Schools



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