Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I override only one method in inheritence?

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.

like image 554
Noich Avatar asked Mar 16 '13 15:03

Noich


People also ask

Can you override an inherited method?

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.

Is method overriding can be done with one class?

The answer is No, you cannot override the same method in one class.

Which method Cannot be overridden?

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.

Can we use method overriding without inheritance?

Rules for Java Method OverridingThere must be an IS-A relationship (inheritance).


1 Answers

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;
        }
};
like image 200
Andy Prowl Avatar answered Sep 22 '22 02:09

Andy Prowl