0

I have declared a class template which contains a virtual method with template parameter as its argument:

template<typename T>
class BaseClass {
    ...
    virtual void SomeMethod(T arg) = 0;
    ...
};

Now, I want to create a class which is derived from the template and override the method:

class DerivedClass : public BaseClass<int> {
    ...
    void SomeMethod(int arg); // Here was "const" modifier in my code
};

But when I want to create an instance of the DerivedClass, compiler complains "cannot declare field ... to be of abstract type". Is there any way how to override a method with template parameter as an argument?

radimoid
  • 199
  • 1
  • 9
  • 1
    [Can't reproduce](http://coliru.stacked-crooked.com/a/1938af1b0c192fc9). Which field is the compiler referencing? There are no fields in your shown code. – chris Mar 02 '21 at 15:33
  • @chris you are not creating an instance, though OP also doesnt show the part of the code that causes the error – 463035818_is_not_an_ai Mar 02 '21 at 15:35
  • Please include a [mcve] – 463035818_is_not_an_ai Mar 02 '21 at 15:35
  • 3
    Seems to work here too: https://godbolt.org/z/rEEjYT – m88 Mar 02 '21 at 15:36
  • 3
    @largest_prime_is_463035818, Neither is the OP's code. I could make this fail to compile in many ways, but I don't want to assume what the actual code is doing. – chris Mar 02 '21 at 15:40
  • I'm sorry, I was inattentive. The error was somewhere else. I added a "const" modifier in my derived class method and thus the error occurred. Anyway, your posts helped me to realize the approach works and that the mistake must be somewhere else. Thank you. – radimoid Mar 03 '21 at 06:23

1 Answers1

1

To override a virtual member function in a template class is like what we do for normal class. A possible reason for that compiler message could be that DerivedClass declared pure virtual function or a pure virtual function of BaseClass<int> doesn't have its implementation in DerivedClass, then DerivedClass is still abstrct class.

ref: https://stackoverflow.com/a/4296300/8336479

The following snippet worked

#include <iostream>

using namespace std;

template<typename T>
class BaseClass
{
public:
  virtual void method(T arg) = 0;

};

class DerivedClass : public BaseClass<int>
{
public:
  void method(int arg) override {
    cout << "arg=" << arg << endl;
  }
};

int main()
{
  BaseClass<int>* pB = new DerivedClass();
  pB->method(12); // print 12 to the console successfully
  delete pB;
  return 0; 
}
M. Zhu
  • 51
  • 4