deeJ
deeJ

Reputation: 682

How to define member function coming from non-template base class

I have a non-templated abstract base class. How do I define the pure virtual function outside derived class?

    #include <iostream>

    class base {
         public:
         virtual void func() = 0;
    };

    template<typename T>
    class der : public base{
    };

    template<typename T>
    void der<T>::func()
    {
         std::cout<<"In Der";
    }

The following error comes up:

template.cpp:13: error: no ‘void der<T>::func()’ member function declared in class ‘der<T>’
template.cpp:13: error: template definition of non-template ‘void der<T>::func()’

Upvotes: 0

Views: 494

Answers (3)

t.dubrownik
t.dubrownik

Reputation: 13432

This will work:

#include <iostream>

class base {
     public:
     virtual void func() = 0;
};

template<typename T>
class der : public base{
  public:
  void func()
  {
       std::cout<<"In Der";
  }
};

It has been recommended to me to drop function definitions straight into templates when possible, except for specializations.

edit: 'inline' was not the best choice of word here

Upvotes: 1

aschepler
aschepler

Reputation: 72463

You must declare the virtual override in the derived class definition.

template <typename T>
class der : public base {
public:
    virtual void func();
};

Upvotes: 2

Erik
Erik

Reputation: 91320

Declare the member function.

template<typename T>
    class der : public base{
    public:
        void func();
    };

There's no automatic declaration of member functions that you may or may not wish to override in a derived class - you have to explicitly declare and define these. Whether the derived class is implemented as a template or not doesn't matter for this.

Upvotes: 5

Related Questions