Function overriding in C++ occurs when a derived class provides its own implementation of a function that is already declared in its base class. The derived class redefines the function with the same name, return type, and parameters as the base class function.
When an overridden function is called through a pointer or reference to the base class, the derived class’s implementation is executed instead of the base class’s implementation. This allows the derived class to modify or extend the behavior of the base class function.
Here’s an example to illustrate function overriding in C++:
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><iostream></span></span>
<span class="hljs-keyword">class</span> <span class="hljs-title class_">Base</span> {
<span class="hljs-keyword">public</span>:
    <span class="hljs-function"><span class="hljs-keyword">virtual</span> <span class="hljs-type">void</span> <span class="hljs-title">display</span><span class="hljs-params">()</span> </span>{
        std::cout << <span class="hljs-string">"Base class display"</span> << std::endl;
    }
};
<span class="hljs-keyword">class</span> <span class="hljs-title class_">Derived</span> : <span class="hljs-keyword">public</span> Base {
<span class="hljs-keyword">public</span>:
    <span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">display</span><span class="hljs-params">()</span> <span class="hljs-keyword">override</span> </span>{
        std::cout << <span class="hljs-string">"Derived class display"</span> << std::endl;
    }
};
<span class="hljs-function"><span class="hljs-type">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    Base* basePtr = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Derived</span>();
    basePtr-><span class="hljs-built_in">display</span>(); <span class="hljs-comment">// Output: Derived class display</span>
    <span class="hljs-keyword">delete</span> basePtr;
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
In this example, the Base class has a virtual function called display(). The Derived class inherits from Base and overrides the display() function with its own implementation. When we create a pointer basePtr of type Base* and assign it an instance of Derived, the display() function of Derived is called even though we’re using a pointer to the base class. This demonstrates polymorphic behavior and the concept of function overriding.
Note the use of the virtual keyword in the base class’s function declaration and the override keyword in the derived class’s function declaration. These keywords are not required but are considered good practice for clarity and to indicate the intention of overriding.
