Cpp - Overload addition + operator

Introduction

The addition operator (+) is a binary operator which adds two operands together.

The next version of the Counter class will be able to add two Counter objects together using the + operator:

Counter var1, var2, var3; 
var3 = var1 + var2; 

Demo

#include <iostream> 
  
class Counter /*w ww. j  a v a 2  s  .  c  o  m*/
{ 
public: 
    Counter(); 
    Counter(int initialValue); 
    ~Counter(){} 
    int getValue() const { return value; } 
    void setValue(int x) { value = x; } 
    Counter operator+(const Counter&); 
   
private: 
    int value; 
}; 
   
Counter::Counter(int initialValue): 
value(initialValue) 
{} 
 
Counter::Counter(): 
value(0) 
{} 
 
Counter Counter::operator+(const Counter &rhs) 
{ 
    return Counter(value + rhs.getValue()); 
} 
 
int main() 
{ 
    Counter alpha(4), beta(13), gamma; 
    gamma = alpha + beta; 
    std::cout << "alpha: " << alpha.getValue() << std::endl; 
    std::cout << "beta: " << beta.getValue() << std::endl; 
    std::cout << "gamma: " << gamma.getValue()  
           << std::endl; 
    return 0; 
}

Result