Reputation: 21
I have a base class Feature
feature.h
#ifndef FEATURE_H
#define FEATURE_H
#include <string>
#include <map>
using namespace std;
template <class T> class Feature
{
public:
virtual map<string, double> calculate(T input)
{
map<string, double> empty;
return empty;
}
};
#endif FEATURE_H
And a child class AvgSentenceLength
avgSentenceLength.h
#include "text.h"
#include "feature.h"
class AvgSentenceLength : public Feature<Text>
{
public:
map<string, double> calculate(Text text);
};
I try to call calculate
method from another file using AvgSentenceLength
object, not directly but still:
map<int, Feature<Text>> features;
AvgSentenceLength avgSentenceLength;
features.insert(pair<int, Feature<Text>>(1, avgSentenceLength));
map<string, double> featuresValues;
featuresValues = features.at(1).calculate(text);
I want to call calculate
method of the child class, but it calls calculate
method of the base class. I can't use pure virtual function in the base class because it is necessary to create objects of this class.
Upvotes: 1
Views: 710
Reputation: 301
simply add a pointer*
to this line:map<int, Feature<Text>> features
so that its like this: map<int, Feature<Text>*> features
.
Upvotes: 1
Reputation: 1325
You need to change map<int, Feature<Text>>
to map<int, Feature<Text>*>
. To Call polymorphic function through its base you need a level of indirection such as a pointer or a reference.
Upvotes: 4