Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ inheritance and function overriding

Tags:

In C++, will a member function of a base class be overridden by its derived class function of the same name, even if its prototype (parameters' count, type and constness) is different? I guess this a silly question, since many websites says that the function prototype should be the same for that to happen; but why doesn't the below code compile? It's a very simple case of inheritance, I believe.

#include <iostream> using std::cout; using std::endl;  class A {}; class B {};  class X { public:     void spray(A&)     {         cout << "Class A" << endl;     } };  class Y : public X { public:     void spray(B&)     {         cout << "Class B" << endl;     } };  int main() {     A a;     B b;     Y y;      y.spray(a);     y.spray(b);      return 0; } 

GCC throws

error: no matching function for call to `Y::spray(A&)' note: candidates are: void Y::spray(B&) 
like image 721
legends2k Avatar asked Jan 29 '10 11:01

legends2k


People also ask

What is function overriding in inheritance?

When the base class and derived class have member functions with exactly the same name, same return-type, and same arguments list, then it is said to be function overriding.

Does C have function overriding?

c is compiled without override.

What is function overriding in C?

Suppose, the same function is defined in both the derived class and the based class. Now if we call this function using the object of the derived class, the function of the derived class is executed. This is known as function overriding in C++. The function in derived class overrides the function in base class.

How function overriding happens?

Inheritance: Overriding of functions occurs when one class is inherited from another class. Overloading can occur without inheritance. Function Signature: Overloaded functions must differ in function signature ie either number of parameters or type of parameters should differ.


2 Answers

The term used to describe this is "hiding", rather than "overriding". A member of a derived class will, by default, make any members of base classes with the same name inaccessible, whether or not they have the same signature. If you want to access the base class members, you can pull them into the derived class with a using declaration. In this case, add the following to class Y:

using X::spray; 
like image 157
Mike Seymour Avatar answered Oct 13 '22 21:10

Mike Seymour


That's so called 'hiding': Y::spray hides X::spray. Add using directive:

class Y : public X { public:    using X::spray;    // ... }; 
like image 27
Alexander Poluektov Avatar answered Oct 13 '22 22:10

Alexander Poluektov