Function overriding in C++
C++ provides function overriding with the use of virtual functions in inheritance. In case the function in the base class is declared as virtual and is overridden in the derived class, the derived class’s implementation will be called if the method is called through the reference or pointer of the base class.
Below is the implementation of function overriding in C++:
#include <iostream>
using namespace std;
class Animal {
public:
virtual void makeSound() {
cout << "Animal makes a sound" << endl;
}
};
class Dog : public Animal {
public:
void makeSound() override {
cout << "Dog barks" << endl;
}
};
int main() {
Animal* animal = new Dog(); // Upcasting
animal->makeSound(); // Output: Dog barks
delete animal;
return 0;
}
Output
Dog barks
Explanation: In C++, function overriding is achieved using virtual functions. The Animal class declares the makeSound() function as virtual, and the Dog class overrides it. When makeSound() is called on a Dog object, it prints “Dog barks”.
Function overriding in programming
Function Overriding is a fundamental principle in object-oriented programming wherein the subclass implements a specific method that has been declared in the superclass. This concept would enable the method calls to be polymorphic where the same method call may behave differently depending on the object which initiated the method call. In this article, we will discuss the basics of Function Overriding along with its implementation in different languages.
Table of Content
- What is Function overriding?
- Function overriding in C++
- Function overriding in Java
- Function overriding in Python
- Function overriding in C#
- Function overriding in Javascript
- Advantages of Function Overriding
- Disadvantages of Function Overriding