c++templatestemplate-specialization

Overriding base class methods in template specialization


I have base template class and I'm creating derived class from it which is template specialization of base class. Base class has a virtual method which I'm trying to overload in derived class and I get the compile error. In fact, I'm not sure whether the way I'm doing is correct or not.

template <class T>
struct BasicContext
{
  BasicContext() {}
  bool operator() (const T i) const
  {
    return isValid(i);
  }
  virtual bool isValid(const T) const
  {
    return true;
  }
  virtual BasicContext* Clone() const
  {
    return(new BasicContext<T>());
  }
};

class Myclass
{
 public:
 Myclass()
 {
 }
};
class MyclassContext : public BasicContext<Myclass*>
{
 public:
 MyclassContext();
 bool isValid(const Myclass* bdry) const override; 
 BasicContext* Clone() const override;
};

And my cpp files looks like this:

bool MyclassContext::isValid(const Myclass* m) const
{
  return true;
}
BasicContext<Myclass*>* MyclassContext::Clone() const
{
   return new MyclassContext();
}

I do get the following compile error:

Severity Code Description Project File Line Suppression State Error C3668 'MyclassContext::isValid': method with override specifier 'override' did not override any base class methods DbgError F:\C++\DbgError\DbgError\Dummy.h 36

Basically the isValid method is not recognized as a base class method in the derived class. How can I override the base class method isValid in the derived class with specialized parameter type? I mean what should be the parameter type?


Solution

  • The problem is that in your base class' isValid(const T) method the const is top-level but in your derived class' isValid(const Myclass* m), you've provided a low-level const.

    Basically, when overriding methods the top-level const must remain top-level and low-level const must remain low-level.

    Solution

    Thus to solve this, change const Myclass* m to Myclass* constm as shown below:

    //-------------------vvvvv---------------------->moved const here
    bool isValid(Myclass*const bdry) const override; 
    

    Make sure you do this in both the declaration and definition of isValid.