Cpp Tutorial: Class template with Overloaded Operators and template Inheritance in C++

In this chapter we shall see below topics:

1. Class template with overloaded operators
2. Template Inheritance

1. Class template with overloaded operators

It is possible to use operator overloading with class template. Below example will show how to achieve the same.

Example:

#include <iostream>
// for more tutorials visit www.ProDeveloperTutorial.com
using namespace std;

template <class T>

class Num  
 {  
    private:
        T number;
        
    public:  
        Num()
        {
            number = 0;
        }
        
        void set_number()
        {
            cout<<"Enter a number"<<endl;
            cin>>number;
        }
        
        Num operator +(Num);
        
        void get_number()
        {
            cout<<number<<endl;
        }
};  
   
template <class T>
Num <T> Num<T> :: operator +(Num <T> c)
{
    Num<T> temp;
    temp.number = number + c.number;
    return temp;
}

int main()
{
    Num <int> n1, n2, n3;
    n1.set_number();
    n2.set_number();
    n3 = n1 + n2;
    n3.get_number();
}

Output:

Enter a number 1
Enter a number 2

3

2. Template Inheritance

It is possible for the base class to act as template class and there can be a class derived from it.

Below is an example to achieve the same.

#include <iostream>       // std::cout
// for more tutorials visit www.ProDeveloperTutorial.com
using namespace std;

template <class T>

class Base 
{
    public:
        T x;
        T y;
};

template <class S>

class Derived : public Base <S>
{
    S z;
public:
    Derived(S a, S b, S c)
    {
        x = a;
        y = b;
        z = c;
    }
    
    void display()
    {
        cout<<"x = "<<x << " y = "<<y <<" z = "<<z<<endl;
    }
};

int main( ) 
{ 
  Derived <int> dObj(10, 20, 30);
  
  dObj.display();
    
  return 0; 
}
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *