In: Computer Science
c++
Write the implementation (.cpp file) of the Counter class of the
previous exercise.
The full specification of the class is:
The previous exercise:
Write the header file (.h file) of a class Counter
containing:
C++ Program:
File: Counter.cpp
#include "Counter.h"
//Static field initialization
int Counter::nCounters = 0;
//Constructor
Counter::Counter(int val)
{
counter = val;
nCounters = nCounters + 1;
counterID = nCounters;
}
//Increment
void Counter::increment()
{
counter = counter + 1;
}
//decrement
void Counter::decrement()
{
counter = counter - 1;
}
//Returns the counter value
int Counter::getValue()
{
return counter;
}
//Returns the counterId value
int Counter::getCounterID()
{
return counterID;
}
File: Counter.h
#ifndef COUNTER_H_INCLUDED
#define COUNTER_H_INCLUDED
class Counter
{
private:
int counter;
int counterID;
static int nCounters;
public:
Counter(int);//Constructor
void increment();
void decrement();
int getValue();
int getCounterID();
};
#endif // COUNTER_H_INCLUDED
File: main.cpp
#include <iostream>
#include "Counter.h"
using namespace std;
int main()
{
//Counter object
Counter cObj(10), cObj1(50);
cout << "\nCounter Id: " <<
cObj.getCounterID();
cout << "\nCounter Value: " << cObj.getValue();
cout << "\nIncrementing counter five times\n";
//Increment
cObj.increment();
cObj.increment();
cObj.increment();
cObj.increment();
cObj.increment();
cout << "\nDecrementing counter\n";
//Decrement
cObj.decrement();
cout << "\nCounter Value: " << cObj.getValue();
cout << "\n\n\nCounter Id: " <<
cObj1.getCounterID();
cout << "\nCounter Value: " << cObj1.getValue();
cout << "\n\n";
return 0;
}
__________________________________________________________________________________________
Sample Run: