C++ function overriding
Created By: chatGPT
In C++, function overriding occurs when a derived class provides a specific implementation of a function that is already defined in its base class. This feature allows for dynamic polymorphism, where the base class pointer can invoke the overridden function of the derived class. To perform function overriding, the function in the base class must be declared as virtual.
class Base {
public:
virtual void show() {
std::cout << "Base class show function called." << std::endl;
}
};
class Derived : public Base {
public:
void show() override {
std::cout << "Derived class show function called." << std::endl;
}
};
In the example above, the
Base
class has a method show()
that is declared as virtual
. The Derived
class overrides this method. The keyword override in the derived class is optional but recommended for clarity and to ensure proper overriding.int main() {
Base* b;
Derived d;
b = &d;
// Calls Derived class show()
b->show();
return 0;
}
When
b->show()
is called, it invokes the show()
method of the Derived
class instead of the Base
class, demonstrating how function overriding works.#include <iostream>
int main() {
Base* b;
Derived d;
b = &d;
// Calls Derived class show()
b->show();
return 0;
}