Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Operator overloading resolution in the hierarchy of classes

I have an hierarchy with an operator() overloading like the following

class Base{
public:
    virtual std::vector<float> operator()(const std::vector<float>& us) const {
        // some implementation like
        // return us;
    }

    virtual float operator()(float u) const = 0;
};

and a derived class

class Derived : public Base{
public:
    float operator()(float u) const override {
        return u;
    }
};

The invocation code looks like the code below (assume, the GetAVectorOfFloats second is indeed std::vector of floats).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Derived d;
auto [_, us] = GetAVectorOfFloats();
auto values = d(us);

However, the compiler (gcc version 11.4.0 (Ubuntu 11.4.0-1ubuntu1~22.04)) spits

error: no match for call to ‘(Derived) (std::vector&)’

I observe, that const std::vector<float>& is not an option (but why?).

In case the code is more explicit

auto values = d.operator()(us);

the error becomes

error: cannot convert ‘std::vector< float>’ to ‘float’

Seems, like I’m missing something very basic? Can not I call the Base’s operator() or is there some special syntax I should use?

>Solution :

This is classic name hiding, nothing at all special about operator overloading:

When lookup for the name operator() is done in Derived (because that’s the type of d) it finds float operator()(float u) const;.

Then name lookup terminates because the name has been found. There will not be any further lookup into the base class.

Solution is to make the other overload visible to name lookup in the scope of the derived class:

class Derived : public Base{
public:
    using Base::operator();
    float operator()(float u) const override {
        return u;
    }
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading