I have a question that I am battling to get my head around. I am given a struct
:
struct Module
{
string moduleName;
string moduleCode;
string lecturer;
string nrStudents;
}
and I am asked to do the following:
- Turn the struct into a class
- Make all member variables private
- Include public member functions for each of the following
- a default constructor that sets the string member variables to blank strings and
int
to0
.- an overloaded constructor that sets the string member variables to specific values.
- member functions to set each of the member variables to a value given as an argument to the function i.e. mutators.
- member functions to retrieve the data from each of the member variables i.e. accessors.
Test the class in a program that instantiates an object of class
Module
(i.e. ‘declare’ an object of ‘type’ Module). The program should then input values for the object (obtained from the keyboard), and use the mutators to assign values to the member variables. Use the accessors to obtain the values of the member variables of the object and display those values on the screen. Test your program with the following input:
Input for member variables of Module object:
Here is my code so far:
Module name: Introduction to Programming
Module code: CSS1515
Lecturer: Mrs Smith
Number of students: 250
#include <iostream>
#include <cstdlib>
using namespace std;
class module
{
private:
string moduleNameVar;
string moduleCodeVar;
string lecturerVar;
int nrStudentsVar;
public:
module( );
//initializes moduleName, moduleCode and lecturer to a blank string
//initializes nrStudent to 0
module(string moduleName, string moduleCode, string lecturer, int nrStudents);
//initializes moduleName, moduleCode and lecturer to a string value
//initializes nrStudent to a number of students
void set(string moduleName, string moduleCode, string lecturer, int nrStudents);
//sets the moduleName, moduleCode, lecturer and nrStudents
};
int main()
{
module exam1("Introduction to Programming","COS1515","Mrs Smith", 250);
}
module::module( ) : moduleNameVar(""), moduleCodeVar(""), lecturerVar(""), nrStudentsVar(0)
{
//body intentionally empty
}
module::module(string moduleName, string moduleCode, string lecturer, int nrStudents)
{
module::set();
}
void module::set(string moduleName, string moduleCode, string lecturer, int nrStudents)
{
moduleNameVar = moduleName;
moduleCodeVar = moduleCode;
lecturerVar = lecturer;
nrStudentsVar = nrStudents;
}
Now what I am trying to understand is why I am asked to use mutators when I've already defined a constructor which could effectively set my member variables. Nonetheless, I am trying to achieve this using: module::set();
, but this is throwing up an error in the compiler: no function for call to module::set()
What am I missing here? How do I go about creating the mutator functions as well as the constructor function?
Note: The accessor function seems easy enough as I would merely be using a get()
function to access the member variables?