Search code examples
c++overriding

Confusion about the phenomenon of overriding


I am little confused about when to say that function is overriden.

My book says "When a derived class creates a function with the same return type and signature as a member function in the base class, but with a new implementation, it is said to be overriding that function."

I am clear what book saying but my question is if I only kept the name same and changed the return type and signature, can I say that function is overriden or is there any different term for it? Like I tried the following code :

#include <iostream>
 using namespace std;
 class Mammal
{
 public:
  int Move() const  
   { 
    cout << "mammal moving\n"; 
    return 1; 
   }
   
  void Move(int x) const 
   {
    cout << "walked " << x << " steps\n"; 
   }
};
  
 class Dog : public Mammal
{
 public:
  void Move()
  { 
   cout << "Dog moving\n";
  }
};
  
 int main()
{
 Dog Moti;
 Moti.Move();
//Moti.Move(2);  error: no matching function for call to 'Dog::Move(int)'
 cout << endl;
 return 0; 
}

Output : Dog moving

So I have Move() method in Dog but it's return type and signature is different than Move() method in Mammal. So is it correct to say Move() in Dog has overridden Move() in Mammal. Why I got this confusion is because when I called Moti.Move(2), I received error. This means void Move(int x) const in Mammal got hidden. But phenomenon of 'hiding' occurs when one of the overloaded methods in base class is overridden in derived class. So that's why I think "Move() in Dog has overridden Move() in Mammal" but according to book definition it seems wrong.

I did some internet search where I found that "in case of virtual functions, return type must be same or covarient" but my question is not about virtual functions or anything. I am just confused about can I say overriding has occurred in the above code or is there any different term for it.


Solution

  • The problem in above code reminds me a very interesting concept of CPP, Name Hiding which simply states that, if we try to overload a method in a derived class, then the compiler will hide the base class method unless we explicitly informs the compiler to include a base class method or we explicitly call the base class method using scope resolution operator like Moti.Mammal::Move(2);

    Do Checkout some related articles:

    https://bastian.rieck.me/blog/posts/2016/name_hiding_cxx/

    overloading base class method in derived class

    https://www.geeksforgeeks.org/g-fact-89/

    P.S: we can't overload methods based on return types, if we try to do so there will be an error.