You are working as a computer engineer in a firm where your task for this week is to
model a Counter class in C++. You are asked to:
• Have a default constructor
• Have a constructor which should take an initial value of count
• Have a copy contractor
• Have a print function to print the count value
• Have a ++ increment operator overladed as prefix and postfix operator
• Have a -- increment operator overladed as prefix and postfix operator
• Have a destructor
Your task is to:
1. Draw the class diagram
2. Implement the class
3. Write the test code to test all the features of your class in the main program.
SOLUTION TO THE ABOVE PROGRAM
SOLUTION CODE
#include<iostream>
using namespace std;
class Counter
{
private:
int count_value;
public:
// Default Constructor
Counter()
{
count_value = 1;
}
// Parameterized Constructor
Counter(int c)
{
count_value = c;
}
// Copy constructor
Counter(const Counter &c1)
{
count_value = c1.count_value;
}
int getcount_value()
{
return count_value;
}
//prit function
void print()
{
cout<<"\nThe count value ="<<getcount_value()<<endl;
}
// member prefix ++count_value
void operator++() { }
// member postfix count_value++
void operator++(int) { };
//Decrements
// member prefix --count_value
void operator--() { }
// member postfix count_value++
void operator--(int) { };
};
int main()
{
//lets make objects for all the constructors
//default constructor
Counter object_1;
//call the print method
object_1.print();
// parameterised constructor is called here
Counter object_2(10);
// call print method
object_2.print();
// Copy constructor is called here
Counter object_3 = object_2;
//call the print function
object_3.print();
//Inccrements
// calls object_1.operator++()
++object_1;
// explicit call, like ++count_value
object_1.operator++();
// calls object_1.operator++(0)
// default argument of zero is supplied by compiler
object_1++;
// explicit call to member postfix count_value++
object_1.operator++(0);
//decrement calls
// calls object_1.operator--()
++object_1;
// explicit call, like --count_value
object_1.operator--();
// calls object_1.operator--(0)
// default argument of zero is supplied by compiler
object_1--;
// explicit call to member postfix count_value--
object_1.operator--(0);
return 0;
}
SAMPLE OUTPUT PROGRAM
Comments
Leave a comment