Search code examples
c++classstatic-variables

Creating a counter inside a template class constructor


I'm stuck on a homework question. We are to create a class template called department, and in the constructor, we need to initialize a counter to be used later. I'm having trouble understanding how to use this counter elsewhere in the program. We were provided with a main.cpp file to use, which we aren't allowed to change. These are the specific instructions I'm stuck on:

You are to create a constructor that may take the department name as an argument, and if it’s null it will ask for a department name to be entered from the keyboard and stores it. It also initializes a counter that keeps track of the number of employees in the array and is maintained when you add, remove, or clear.

The only way I've managed to get it to work is by setting the constructor to accept two arguments, one for department name, and one for the counter. But the main.cpp file provided only allows for one argument, name.

Department.h:

template <class Type>
class Department {

  private:
    std::string name;
   ...

  public:
  Department(const std::string & deptName)
  {
    int counter = 0;
    name = deptName;
  }
... 
};

Main.cpp (provided, and not allowed to change):

int main()
{   Department dept1("CIS");   // a department
...

Is there a way to use the counter initialized in the constructor outside of the constructor without changing the argument requirements for Department?


Solution

  • Is there a way to use the counter initialized in the constructor outside of the constructor without changing the argument requirements for Department?

    Sure. Make a counter member variable, and use it in the methods you write for your class.

    template <class Type>
    class Department {
    
    private:
      std::string name;
      int counter;
    
    public:
      Department(const std::string & deptName)
      {
        counter = 0;     // note `int` not needed, as counter is already declared
        name = deptName;
      }
    
      int getCounter()
      {
        return counter;
      }
    
      void addEmployee(std::string name)
      {
        counter++;
        // do something with adding employees
      }
    
      // other methods
    };