dimanche 1 novembre 2020

Derived class hiding base class same name method

I was reading this article and it states

This calls Derived::f( complex ). Why? Well, remember that Derived doesn't declare "using Base:f;", and so clearly Base::f( int ) and Base::f( double ) can't be called.

I decided to try this out and used this code

class Base {
public:
    virtual void f( int ) {
        cout << "Base::f(int)" << endl;
    }

    virtual void f( double ) {
        cout << "Base::f(double)" << endl;
    }

    virtual void g( int i = 10 ) {
        cout << i << endl;
    }
};

class Derived: public Base {
    using Base::f;
    
public:
    void f( complex<double> ) {
        cout << "Derived::f(complex)" << endl;
    }

    void g( int i = 20 ) {
        cout << "Derived::g() " << i << endl;
    }
};


int main() {
    Derived d;

    d.f(1.0);        
}

I get the error main.cpp: In function 'int main()':

main.cpp:43:16: error: 'virtual void Base::f(double)' is inaccessible within this context
   43 |         d.f(1.0);

My question is how do I use using Base::f; and how do I fix this issue ?

Aucun commentaire:

Enregistrer un commentaire