My C++
code is as follows:
#include<iostream>
using namespace std;
class A
{
public:
virtual void f(int i)
{
cout << "A's f(int)!" << endl;
}
void f(int i, int j)
{
cout << "A's f(int, int)!" << endl;
}
};
class B : public A
{
public:
virtual void f(int i)
{
cout << "B's f(int)!" << endl;
}
};
int main()
{
B b;
b.f(1,2);
return 0;
}
during compilation I get:
g++ -std=c++11 file.cpp
file.cpp: In function ‘int main()’:
file.cpp:29:9: error: no matching function for call to ‘B::f(int, int)’
file.cpp:29:9: note: candidate is:
file.cpp:20:16: note: virtual void B::f(int)
file.cpp:20:16: note: candidate expects 1 argument, 2 provided
When I tried to use override after B's f(int), I got the same error.
Is it possible in C++ to override only 1 method? I've been searching for a code example using override
that will compile on my machine and haven't found one yet.
To override an inherited method, the method in the child class must have the same name, parameter list, and return type (or a subclass of the return type) as the parent method. Any method that is called must be defined within its own class or its superclass.
The answer is No, you cannot override the same method in one class.
Methods a Subclass Cannot Override Also, a subclass cannot override methods that are declared static in the superclass. In other words, a subclass cannot override a class method.
Rules for Java Method OverridingThere must be an IS-A relationship (inheritance).
The problem is that your virtual function f()
in class B
hides A
's non-virtual overload with an identical name. You can use a using
declaration to bring it into scope:
class B : public A
{
public:
using A::f;
// ^^^^^^^^^^^
virtual void f(int i)
{
cout << "B's f(int)!" << endl;
}
};
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