c++operator-overloadingoperator-keywordname-hiding

c++ if several operator is defined in a class as virtual, does child need to override them all in order to compile?


I have the following classes,

class Base {
public:
    virtual void operator()(string a) {}
    virtual void operator()(int a) {}
};

class Child: public Base {
private:
    std::vector<double> child_vec;
public:
    void operator()(string a) override {
        cout << a << endl;
    }

};

int main() {
    Child child;
    child(9);
}

The above code snippet gives compile time error, ambiguous overload. but if I put virtual void operator()(int a) {} as a normal function, it works,

class Base {
public:
    virtual void operator()(string a) {}
    virtual void test(int a) {}
};

class Child: public Base {
private:
    std::vector<double> child_vec;
public:
    void operator()(string a) override {
        cout << a << endl;
    }

};

int main() {
    Child child;
    child.test(9);
}

Does that mean in case of several virtual operators in base class, I need to override all of them?


Solution

  • The problem is the operator() defined in Child hides operator()s defined in Base.

    You can introduce them into Child via using.

    class Child: public Base {
    private:
        std::vector<double> child_vec;
    public:
        using Base::operator();
        void operator()(string a) override {
            cout << a << endl;
        }
    };
    

    In your 2nd code snippet you change the name to test then there's no such name hiding trouble.