FUNCTION OVERRIDING

 FUNCTION OVERRIDING

·       A feature of runtime polymorphism

·       derived class provides its own implementation of a function that is already defined in the base class.

·       Same function name, Same return type, Same parameter list occur in inheritance.
Requires virtual keyword to achieve runtime polymorphism.

·       Modify or extend the behaviour of a function already defined in the base class.

 

Example:

  • Base class has a void show() method, and Derived class wants a different show() → override it

Rules of Function Overriding

  1. Function name must be the same.
  2. Signature must be the same.
  3. Return type must be the same (except covariant return types).
  4. Base class function should be declared virtual to enable polymorphism.
  5. Base class pointer or reference should call the function.
  6. Access modifiers may differ, but are recommended same or more accessible.

 Types

  1. Simple overriding
  2. Overriding with virtual keyword
  3. Overriding with the override keyword (C++11)
  4. Using final to stop overriding

 

Example:-

#include <iostream>

using namespace std;

 

class Base {

public:

    virtual void show() {

        cout << "Base class show()" << endl;

    }

};

 

class Derived : public Base {

public:

    void show() {   // overriding

        cout << "Derived class show()" << endl;

    }

};

 

int main() {

    Base *ptr;

    Derived d;

 

    ptr = &d;        // base pointer → derived object

    ptr->show();     // calls Derived::show()

 

    return 0;

}

 

OUTPUT

Derived class show()


 


Post a Comment

0 Comments