// Listing 14.4
// Add Function
#include <iostream>
class Counter
{
public:
Counter();
Counter(int initialvalue);
~Counter() {}
int GetItsVal()const {return itsVal; }
void SetItsVal(int x) {itsVal = x; }
Counter Add(const Counter &);
private:
int itsVal;
};
Counter::Counter(int initialValue):
itsVal(initialValue)
{}
Counter::Counter():
itsVal (0)
{}
Counter Counter::Add(const Counter & rhs)
{
return Counter(itsVal+ rhs.GetItsVal());
}
int main()
{
Counter varOne(2), varTwo(4), varThree;
varThree = varOne.Add(varTwo);
std::cout << "varOne: " << varOne.GetItsVal()<< std::endl;
std::cout << "varTwo: " << varTwo.GetItsVal() << std::endl;
std::cout << "varThree: " << varThree.GetItsVal()
<< std::endl;
std::cout << "Press Enter or Return to continue.\n";
std::cin.get();
return 0;
}
I was wondering if anybody could help me understand the above code a little bit better? The analysis is from my book. I have asked questions on the parts I don't understand. Many thanks in advance!!
Analysis:
The Add() function is declared on line 12. It takes a constant Counter reference,
which is the number to add to the current object.(which is varOne?)It returns a Counter object, which is the result to be assigned to the left side of the assignment statement, as shown on line 35.( which is varThree?) That is, varOne is the object, varTwo is the parameter to the Add() function, and the result is assigned to varThree.
Return Counter(itsVal+ rhs.GetItsVal()); Is itsVal+rhs.GetItsVal()); VarOne + VarTwo? and is Return Counter (Var three)?