I have the following code:
struct Abs {
virtual void f(int x) = 0;
virtual void f(double x) final { std::cout << 2; }
};
struct Sub: public Abs {
void f(int x) final { std::cout << 1; }
};
Abs
is an abstract class which comprises a pure member function void f(int)
and its overloaded version void f(double x)
, which is no longer pure and final
. If I try to override void f(int)
in the derived struct Sub
, it shadows void f(double)
and the following main
function prints 1
, converting 1.01
to int
:
int main() {
Sub x = {};
x.f(1.01);
return 0;
}
How do I overcome this problem? Also, why does it work like that?
By Definition : When a class defines two or more than two methods with same name but different in parameters, we call it method overloading while when a subclass defines a method with same name and same in parameters (number and type of parameters) as in parent class, we call it method overriding.
Note: Final method can not be overridden. See the below example. Main. java:14: error: sum (int, int) in Main cannot override sum (int, int) in SumTest public void sum (int num1, int num2) { ^ overridden method is final Main. java:22: error: cannot find symbol main. show(); ^ symbol: method show () location: variable main of type Main 2 errors
When this method is called by an object of the subclass, then always the Overridden version will be called. In other words, the method which was Overridden in the superclass will become hidden.
1 Method overriding is defining a method in the child class with the same method name and same method signature which is already written in the parent class. 2 Return type of overridden method can be a subtype of the return type of parent class method. E.g. ... 3 It can’t have a lower access modifier. ... More items...
Given x.f(1.01);
, the name f
is found in the scope of class Sub
, then name lookup stops; the scope of Abs
won't be examined. Only Sub::f
is put in overload set and then overload resolution is performed.
... name lookup examines the scopes as described below, until it finds at least one declaration of any kind, at which time the lookup stops and no further scopes are examined.
You can use using
to introduce the names of Abs
into Sub
, then Abs::f
could be found and take part in overload resolution too.
struct Sub: public Abs {
using Abs::f;
void f(int x) final { std::cout << 1; }
};
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