Page 83 - Modular_V2.0_C++_Flikpbook
P. 83

Example: The + (plus) operator performs addition when used with integers and concatenation
                    when used with strings.

                 3.   Function Overriding: The process of redefining a function with the same name, return type,
                    and argument list in both the subclass and the superclass.
                 Let's create a program to understand the concept better.

                 Program 5: Demonstrating function overriding.

                 #include<iostream.h>
                 #include<conio.h>
                 class Animal

                 {
                 public:
                     void makeSound()
                                                                                          DOSBox 0.74, Cpu speed: max 100%
                     {
                                                                                      Dog Sound: D_
                         cout<< "Animal Sound: A";
                     }

                 };
                 class Dog : public Animal
                 {

                 public:
                     void makeSound()  // Overriding the base class function
                     {

                         cout<< "Dog Sound: D";
                     }
                 };

                 void main()
                 {
                     clrscr();

                     Dog d;
                     d.makeSound();  // Calls the overridden function in Dog class
                     getch();

                 }
                 This program demonstrates function overriding, where the Dog class redefines the makeSound()
                 function of the  Animal class. The base class prints a generic  sound, while the derived  class
                 provides  a  specific  barking  sound.  When  a  Dog object  calls  makeSound(),  the  overridden
                 function runs, showcasing runtime polymorphism.






                                                                                                                  81
                                                                                                 OOP Concepts
   78   79   80   81   82   83   84   85   86   87   88