user1529412
user1529412

Reputation: 3756

How to inherit from Template class C++

Its been a while for C++, I have a class Number and several subclasses like Integer, Decimal.. I would like to override == operator to compare when two nums are numerically equal... I have something like the following, but can't seem to figure out the syntax for subclass inheriting from template class as well as syntax for overriding == operator in subclass...

template class <T>
class Number{
  T data;
   Number(T num) { data = num ;}
  boolean operator==(T &other){ return data == other; }
 }

class Integer : public Number{
 int iData;
 Integer(int i) { iData = i ; }
 boolean operator==(Integer &other){ return idata == other.iData; }

 }

Upvotes: 3

Views: 25642

Answers (3)

vsoftco
vsoftco

Reputation: 56557

You need to specify a specialization, like Number<int>. Otherwise you cannot inherit from a template, unless your derived class is a template itself. There are some other errors in your code, like the ones mentioned in the comments, as well as the operator== operator, which should take const Number<T>& as a parameter. So in your case use e.g.

class Integer : public Number<int>

Once you do this, there is no need anymore for implementing the operator== in the derived class, since it will be inherited. Full working code below:

#include <iostream>

template <class T>
class Number 
{
public:
    T data;
    Number(T num): data(num){}
    bool operator==(const Number<T> &other) { return data == other.data; }
};

class Integer : public Number<int> 
{
    using Number<int>::Number; // inherit the constructor
};

int main()
{
    Integer i1 = 10, i2 = 20;
    std::cout << std::boolalpha << (i1 == i2);
}

Live on Coliru

Upvotes: 5

Yan Zhu
Yan Zhu

Reputation: 4346

Use

template<class T>
class Number{
  T data;
   Number(T num) { data = num ;}
  boolean operator==(T &other){ return data == other; }
 };

template<typename T>
class Integer : public Number<T> {
 int iData;
 Integer(int i) { iData = i ; }
 boolean operator==(Integer &other){ return idata == other.iData; }

 }

Upvotes: 1

sp2danny
sp2danny

Reputation: 7689

either

template<class T>
class Integer : public Number<T> {

or

class Integer : public Number<int> {

depending on if you want Integer to be a template too or not

Upvotes: 2

Related Questions