I've a class below that creates records of students grades. The constructor allocates memory for the array and sets a default value to each element in the array. I have to pass in the value of this default value. My question is, can I allocate the memory and initialize the values of an array with a construct initialization list or in any other way. I don't what to use dynamic allocation new and delete.
//header file for main.cpp
#include<iostream>
using namespace std;
const int SIZE = 5;
template <class T>
class StudentRecord
{
private:
const int size = SIZE;
T grades[SIZE];
int studentId;
public:
StudentRecord(T defaultInput);//A default constructor with a default value
void setGrades(T* input);
void setId(int idIn);
void printGrades();
};
template<class T>
StudentRecord<T>::StudentRecord(T defaultInput)
{
//we use the default value to allocate the size of the memory
//the array will use
for(int i=0; i<SIZE; ++i)
grades[i] = defaultInput;
}
template<class T>
void StudentRecord<T>::setGrades(T* input)
{
for(int i=0; i<SIZE;++i)
{
grades[i] = input[i];
}
}
template<class T>
void StudentRecord<T>::setId(int idIn)
{
studentId = idIn;
}
template<class T>
void StudentRecord<T>::printGrades()
{
std::cout<<"ID# "<<studentId<<": ";
for(int i=0;i<SIZE;++i)
std::cout<<grades[i]<<"\n ";
std::cout<<"\n";
}
#include "main.hpp"
int main()
{
//StudentRecord is the generic class
StudentRecord<int> srInt();
srInt.setId(111111);
int arrayInt[SIZE]={4,3,2,1,4};
srInt.setGrades(arrayInt);
srInt.printGrades();
return 0;
}