Using class

Define a class for a type called CounterType . An object of this type is used to count things, so it records a count that is a nonnegative whole number. Include a mutator function that sets the counter to a count given as an argument. Include member functions to increase the count by one and to decrease the count by one. Be sure that no member function allows the value of the counter to become nega- tive. Also, include a member function that returns the current count value and one that outputs the count. Embed your class definition in a test program.

#include <iostream>
using namespace std;

class CounterType
{
private:
int count;

public:
CounterType();
CounterType(int newcount);
void Increase();
void Decrease();
int getcount(); // Accessor
void setcount(int newcount); // Mutator
};

void main()
{
CounterType counts;
counts.Increase();
counts.Decrease();

}
CounterType::CounterType(){
count=5;
}

CounterType::CounterType(int newcount)
{
count=newcount;
}

void CounterType:: Increase()
{
count++;
}

void CounterType:: Decrease()
{
if (count<=0)
{
count=0;
}
else
{
count--;
}

}

int CounterType::getcount()
{
return(count);
}

void CounterType::setcount(int Newcount)
{
setcount(5);
}


Am I on the right track?
setcount is implemented incorrectly. It is defined recursively and doesn't use the parameter that is passed to it. If you call it, it will call itself over and over again until it overruns the stack. It should look like this:
1
2
3
4
void CounterType::setcount(int newCount)
{
     count = newCount;
}

There was also a thread recently about int main() vs void main(). Since you're probably going to be running in hosted environments (not freestanding) you should get into the habit of using int main().
Last edited on
Thank you very much.
Topic archived. No new replies allowed.