乐闻世界logo
搜索文章和话题

What is function overriding in C++?

1个答案

1

In C++, Function Overriding is a fundamental concept in object-oriented programming, primarily used to achieve polymorphism. When a class (referred to as a derived class) inherits from another class (referred to as a base class), the derived class can define a function with the same name, return type, and parameter list as in the base class. This function defined in the derived class overrides the function with the same name in the base class.

The primary purpose of function overriding is to allow the derived class to modify or extend the behavior inherited from the base class. At runtime, this enables objects to call functions in the derived class through base class pointers or references, forming the basis of polymorphic behavior.

Example:

Assume we have a base class Animal and a derived class Dog, as shown below:

cpp
class Animal { public: virtual void speak() { cout << "Some animal sound" << endl; } }; class Dog : public Animal { public: void speak() override { // The `override` keyword explicitly indicates overriding cout << "Woof" << endl; } };

In this example, the Dog class overrides the speak method in the Animal class. When calling the speak method through an Animal-type pointer or reference, if it points to a Dog object, the speak method of the Dog class is invoked:

cpp
Animal* myPet = new Dog(); myPet->speak(); // Outputs "Woof"

Here, although myPet is an Animal-type pointer, it actually points to a Dog object, so the speak function overridden in Dog is called, demonstrating polymorphism.

Using the override keyword is a good practice introduced in C++11, which allows the compiler to verify that the function correctly overrides the base class method. If not overridden correctly (e.g., mismatched parameter types), the compiler reports an error. This helps prevent errors caused by typos or mismatched function signatures.

2024年7月16日 14:15 回复

你的答案