Method func
from DerivedClass
override the method func
and all its overloads from BaseClass
.
#include <cstdio>
class BaseClass
{
public:
void func(int a){puts("BaseClass::func(int)");};
void func(int a, int b){puts("BaseClass::func(int, int)");};
void func(int a, int b, int c){puts("BaseClass::func(int, int, int)");};
//...
};
class DerivedClass : public BaseClass
{
public:
void func(int a){puts("DerivedClass::func(int)");}
//...
};
int main()
{
DerivedClass obj;
obj.func(0);
obj.func(0, 0); // error
obj.func(0, 0, 0); // error
return 0;
}
How can I fix this code to end up on the screen was derived:
DerivedClass::func(int)
BaseClass::func(int, int)
BaseClass::func(int, int, int)
Edit 1
In functions main
should not change anything
Rules for method overriding:The argument list should be exactly the same as that of the overridden method. The return type should be the same or a subtype of the return type declared in the original overridden method in the super class.
Method overriding, in object-oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes.
Therefore, you cannot override two methods that exist in the same class, you can just overload them.
If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java. In other words, If a subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method overriding.
The derived class's member function doesn't override the base class ones, it hides them. To bring them all to scope, use a using
declaration:
class DerivedClass : public BaseClass
{
public:
void func(int a){puts("DerivedClass::func(int)");}
using BaseClass::func;
//...
};
Live example
It's by design: the phenomenon is called "name hiding".
[Short answer]:
C++ doesn't like the idea that a long-standing behavior as calling one base-function with a specific set of parameters can be modified in one of your subclasses and chose to hide all overloads in every base class to solve this.
[Long answer] here: https://stackoverflow.com/a/1629074/1938163
As a workaround you can cast the object to the appropriate base and call the functions you need (there's a cast penalty though), or better call the function you need directly by specifying its base class
int main()
{
DerivedClass obj;
obj.func(0);
obj.BaseClass::func(0,0);
return 0;
}
Live Example
or you can un-hide them with a "using directive"
class DerivedClass : public BaseClass
{
public:
void func(int a){puts("DerivedClass::func(int)");}
using BaseClass::func;
//...
};
Live Example
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