Search code examples
c++templatespure-virtual

C++ Abstract Base Template Class Non-Void Method


I have an abstract base template class that contains members functions, some that are void, others returning data types ranging from primitive data types to the template parameter data type. I am still new to C++, and I know that I don't necessarily have to implement the pure virtual functions in the base class unless I wish to call them in the derived classes. This idea was fine for member functions that had no return value. For a function that returned an integer, I returned a 0. But when I got to a function that returned a reference to T, the template parameter, I did not know what to do. I tried the two following returns.

template <typename T>
T& AbstractBaseClass<T>::function(){
return T();
}

and

template <typename T>
T& AbstractBaseClass<T>::function(){
return T& tmp= T();
}

But neither seem to work, and I cannot not define these functions because I get an undefined reference error for the functions. I assume this error is because the functions are templates. What is the appropriate way to implement a non-void pure virtual function?

template <typename T>
class AbstractBaseClass{
public:
virtual ~AbstractBaseClass() = 0;
T& function();
}

template <typename T>
T& AbstractBaseClass<T>::function(){
    //what must I do here when I don't have any member variable
}

Solution

  • Here is an example of a pure virtual function and a derived class that implements it (some member functions omitted for clarity):

    template <class T>
    class Base
    {
       public:
         virtual T& get() = 0;
         virtual ~Base() = 0;
    };
    
    template <class T>
    Base<T>::~Base() {}
    
    template <class T>
    class Derived: public Base<T>
    {
       T t;
       public:
         T& get() override { return t; }
    };
    

    Note how get() in Base has no implementation, and the implementation of get in Derived uses a new data member not available in Base.

    Note also that a pure virtual destructor, unlike other pure virtual functions, must have an implementation. Normally one doesn't need a pure virtual destructor if there are other pure functions in the class though. It is shown here for illustration.