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
- Function
name must be the same.
- Signature
must be the same.
- Return
type must be the same (except covariant return types).
- Base
class function should be declared virtual to enable polymorphism.
- Base
class pointer or reference should call the function.
- Access
modifiers may differ, but are recommended same or more accessible.
Types
- Simple
overriding
- Overriding
with virtual keyword
- Overriding
with the override keyword (C++11)
- 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()
0 Comments