Search Your Topic

config
Saturday, 17 June 2017 07:28

C++ Function Overriding

Written by
Rate this item
(0 votes)

If derived class defines same function as defined in its base class, it is known as function overriding in C++. It is used to achieve runtime polymorphism. It enables you to provide specific implementation of the function which is already provided by its base class.

C++ Function Overriding Example

Let's see a simple example of Function overriding in C++. In this example, we are overriding the eat() function.

 
  1. #include <iostream>  
  2. using namespace std;  
  3. class Animal {  
  4.     public:  
  5. void eat(){    
  6. cout<<"Eating...";    
  7.     }      
  8. };   
  9. class Dog: public Animal    
  10. {    
  11.  public:  
  12.  void eat()    
  13.     {    
  14.        cout<<"Eating bread...";    
  15.     }    
  16. };  
  17. int main(void) {  
  18.    Dog d = Dog();    
  19.    d.eat();  
  20.    return 0;  
  21. }  

Output:

Eating bread...
Read 29 times
Anish Sir

"I am delighted once again to pen the welcome note to the Tosh!Yas Technologies ."

 Call +91 74 88 34 7779  | Email : anishsingh@live.com

toshiyas.in

Leave a comment

Make sure you enter all the required information, indicated by an asterisk (*). HTML code is not allowed.