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;
}
-
1any reason you can't use std::vector?UKMonkey– UKMonkey2017年12月13日 11:52:04 +00:00Commented Dec 13, 2017 at 11:52
-
C++ does not have runtime variable length array except through memory allocation. Your choices are therefore to use allocation or use an array that is large enough for the maximum possible value of SIZE and storing the actual number used in each object.Justin Finnerty– Justin Finnerty2017年12月13日 15:27:04 +00:00Commented Dec 13, 2017 at 15:27
1 Answer 1
Yes you can. Following is an example. Here you can see it working:
class A
{
int valLen;
int* values;
vector<int> vect;
public:
A(int len, ...)
{
va_list args;
va_start(args, len);
valLen = len;
for(int i=0; i<valLen; i++)
{
vect.push_back(va_arg(args, int));
}
values = &vect[0];
va_end(args);
}
void print()
{
for(int i=0; i<valLen; i++)
cout << values[i]<<endl;
}
};
int main()
{
A aVals[] ={A(3, 50,6,78), A(5, 67,-10,89,32,12)};
for(int i=0; i<2; i++)
{
aVals[i].print();
cout<<"\n\n";
}
return 0;
}
Note: Very first argument of constructor is the number count i.e. number of values to be passed. If count is fixed, then you can skip and make appropriate change in constructor.