c++inheritanceoverridingvirtualoperator-keyword

c++ calling operator()() in derived class not working


I have a abstract base class having operator()(), operator and virtual operator()(...) methods. In derived class i am overriding the virtual method but i cannot call the opearator()() method. And i have no idea why?

#include <iostream>
#include <vector>

using Date = size_t;
using Period = size_t;

// abstract series
template <class T>
class SeriesBase {
public:
    T operator()() const {
        return operator()(0);
    }

    T operator[](const Period period) const {
        return operator()(period);
    }

    virtual T operator()(const Period period) const = 0;
};

template <class T>
class Series : public SeriesBase<T> {
public:
};

// concrete series
class DateSeries : public Series<Date> {
public:
    Date operator()(const Period period) const override {
        return 20231212;    // or return something from vector
    }

private:
    std::vector<Date>   values;
};

int main() {
    DateSeries          dateSeries;
    dateSeries();       // not working ???
    dateSeries[1];      // working
    dateSeries(1);      // working
}

Solution

  • It gets shadowed by the derived class operator() even if it has different arguments (and different const[&][&&] qualifier). Even with many years of experience I get tripped by this.

    You need to do this:

    // concrete series
    class DateSeries : public Series<Date> {
    public:
        using Series<Date>::operator();
        Date operator()(const Period period) const override {
            return 20231212;    // or return something from vector
        }
    
    private:
        std::vector<Date>   values;
    };
    

    https://godbolt.org/z/rYPa53sd9

    Interestingly you don't need/have to put the argument types of the base class.

    Note that this has nothing to do with the classes being templated or the virtual keyword. (https://godbolt.org/z/PzofaYv3s)