This is possibly a noob question, sorry about that. I faced with a weird issue recently when trying to mess around with some high level stuff in c++, function overloading and inheritance.
I'll show a simple example, just to demonstrate the problem;
There are two classes, classA
and classB
, as below;
class classA{ public: void func(char[]){}; }; class classB:public classA{ public: void func(int){}; };
According to what i know classB
should now posses two func(..)
functions, overloaded due to different arguments.
But when trying this in the main method;
int main(){ int a; char b[20]; classB objB; objB.func(a); //this one is fine objB.func(b); //here's the problem! return 0; }
It gives errors as the method void func(char[]){};
which is in the super class, classA
, is not visible int the derived class, classB
.
How can I overcome this? isn't this how overloading works in c++? I'm new to c++ but in Java, i know I can make use of something like this.
Though I've already found this thread which asks about a similar issues, I think the two cases are different.
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.
This feature is present in most of the Object Oriented Languages such as C++ and Java. But C doesn't support this feature not because of OOP, but rather because the compiler doesn't support it (except you can use _Generic).
The reason is the same as explained in the case of the C++ program. In C#, just like in C++, there is no overload resolution between class Base and class Derived. Also, there is no overloading across scopes and derived class scopes are not an exception to this general rule.
Note: In a subclass, you can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass instance methods—they are new methods, unique to the subclass.
All you need is a using
:
class classB:public classA{ public: using classA::func; void func(int){}; };
It doesn't search the base class for func
because it already found one in the derived class. The using
statement brings the other overload into the same scope so that it can participate in overload resolution.
It is well explained for example in this question's answers:
Why should I use the "using" keyword to access my base class method?
In short, compiler will stop searching for matching methods from parent classes, when it finds matching method name in current class, even when that method is not compatible. I guess this allows some automatic type conversions to work more logically, without needing to override so many parent class methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With