Function overriding in C++ is a feature of object-oriented programming that allows a subclass to provide a specific implementation of a method that is already defined in its superclass. This concept is part of polymorphism, where the subclass can override a method of its superclass to exhibit behavior that’s appropriate to the subclass object.
Here are some key points about function overriding in C++:
Same Signature: The function in the subclass must have the same name, return type, and parameters as the one in its superclass. Inheritance: Function overriding can only occur when one class is a subclass of another.
Virtual Functions: In C++, the function to be overridden in the superclass should be declared with the virtual keyword. This tells the compiler that the function is intended to be overridden in derived classes.
Access Level: The overriding function in the subclass should have the same or less restrictive access level. For example, if the function in the superclass is public, the overriding function can be public but not private or protected.
class Animal {
public:
virtual void makeSound() {
cout << "Animal sound" << endl;
}
};
class Dog : public Animal {
public:
void makeSound() { // Overriding function
cout << "Woof!" << endl;
}
};
int main() {
Animal* myAnimal = new Dog();
myAnimal->makeSound(); // Outputs: Woof!
delete myAnimal;
return 0;
}