Can I override only one method in inheritance?

My C++code is as follows:

#include<iostream>
using namespace std;

class A
{
    public:
        virtual void f(int i)
        {
            cout << "A f(int)!" << endl;
        }
        void f(int i, int j)
        {
            cout << "A f(int, int)!" << endl;
        }
};

class B : public A
{
    public:
        virtual void f(int i)
        {
            cout << "B f(int)!" << endl;
        }
};

int main()
{
    B b;
    b.f(1,2);
    return 0;
}

at compile time 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 the override after B f (int), I got the same error.

Is it possible to override only one method in C ++? I was looking for sample code using overridethat will compile on my machine and have not found it yet.

+5
source share
5 answers

You redefine the name "f" as the name of the method. Therefore, any overload will also be canceled.

You can use the keyword usingto tell the compiler to also look at the base class:

class B : public A
{
    public:
        using A::f;
        virtual void f(int i)
        {
            cout << "B f(int)!" << endl;
        }
};
+5
source

, f() B A . using, :

class B : public A
{
    public:
        using A::f;
    //  ^^^^^^^^^^^

        virtual void f(int i)
        {
            cout << "B f(int)!" << endl;
        }
};
+10

, ++. , .

, , , . , , .

, , :

class B : public A
{
    public:
        using A::f;
        virtual void f(int i)
        {
            cout << "B f(int)!" << endl;
        }
};

, using . , using A::f; f(int), B (A::f(int) B::f(int)). ++ , , () b.f(3); main ( using A::f; ), - B::f(int) .

+4
+1
source

Yes, it is possible to override only one class method, make it virtual. Non-virtual will be obscured when declared in an inherited class.

0
source

All Articles