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

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 :

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

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)

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