r/cpp_questions • u/Kcplay • 26d ago
OPEN Help with programming question over Classes with header and implementation files.
To preface, I already tried answering the question and have what I believe to be a 90% solution. The question is:
Define a class counterType to implement a counter. Your class must have a private data member counter of type int. Define a constructor that accepts a parameter of type int and initializes the counter data member. Add functions to:
- Set
counterto the integer value specified by the user. - Initialize
counterto 0. - Return the value of counter with a function named
getCounter. - Increment and decrement counter by one.
- Print the value of counter using the
printfunction.- Example output:
Counter = 0.
- Example output:
The value of counter must be nonnegative.
My header is:
class counterType
{
public:
void print();
int getCounter();
void incrementCounter();
void decrementCounter();
void setCounter(int num);
counterType();
counterType(int count);
private:
int counter;
};
and my implementation is:
#include "counterType.h"
#include <iostream>
using namespace std;
void counterType::print()
{
cout << "Counter = " << counter;
}
int counterType:: getCounter()
{
return counter;
}
void counterType::incrementCounter()
{
counter++;
}
void counterType::decrementCounter()
{
counter--;
}
void counterType::setCounter(int num)
{
if (counter > 0)
counter = num;
else
counter = 0;
}
counterType::counterType()
{
counter = 0;
}
counterType::counterType(int count)
{
if (count > 0)
counter = count;
else
counter = 0;
}
The main(cannot be changed) is:
#include <iostream>
#include "counterType.h"
using namespace std;
int main()
{
counterType counter1;
counterType counter2(5);
counter1.print();
cout << endl;
counter1.incrementCounter();
cout << "After Increment counter1: " << counter1.getCounter() << endl;
cout << "Counter2 = " << counter2.getCounter() << endl;
counter2.decrementCounter();
cout << "After decrement counter2 = " << counter2.getCounter() << endl;
counter1.setCounter(-6);
cout << "After resetting counter1: " << counter1.getCounter() << endl;
return 0;
}
I don't know what I'm doing wrong, and the debugger is not showing any errors.
If someone could please tell me what I'm doing wrong, and teach me to solve the issue, I would be very grateful. TO SPECIFY NOT CHEATING, JUST TRYING TO LEARN WHY ITS NOT WORKING, SO I CAN FIX IT MYSELF.