Search code examples
c++templatesinheritancevirtual

How to write the definition of a derived class in c++?


I don't know the syntax for writing the definition of a class function with templates.

I get an error, the complier expected ; , so that be void plus; Anyone knows to fix that!

template<class Type 
class basic{
 protected:
    Type x;
 public:
    int value;
    //virtual void  print() =0; 
  basic(Type xArg):x(xArg){}
}; 

template<class Type>
class plus:public basic<Type>{
 public: 
  Type y;
  plus(Type xArg, Type yArg):basic<Type>(xArg),y(yArg){}
  void print(); 

};

//template<class Type> 
void plus<Type>::print(){ 
  cout << "x : " << x << endl;
  cout << "y : " << y << endl;

}

Solution

  • Let's say we have a base class:

    template<class T> 
    class MyBase {
       public:
        T value;
    
        virtual void print() {
            std::cout << "MyBase.value: " << value;
        }        
        virtual ~MyBase() = default; 
    };
    

    We can derive it and override print like this. It doesn't have to be a template, but I'm using one in the example.

    template<class T>
    class MyDerived : MyBase<T>
    {
       public:
        void print() override {
            std::cout << "MyDerived.value: " << MyBase<T>::value;
        }
    };
    

    In addition, something I like to do is use base to represent the base class:

    template<class T>
    class MyDerived : MyBase<T>
    {
       public:
        using base = MyBase<T>; // Use this to indicate the base
        void print() override {
            std::cout << "MyDerived.value: " << base::value << '\n';
        }
    };