Challenge: Managing Data with Constructors and Destructors
Swipe to start coding
Imagine you are building a student grading system. You need to create a GradesManager class that manages a list of student grades.
Your task is to implement a constructor that initializes a dynamic array of grades and a single method that calculates the average grade. The destructor should release the allocated memory automatically.
-
Implement a constructor using initializer list syntax:
- It should take
sizeas a parameter. - Allocate a dynamic array of integers called
gradeswith the givensize. - Use a
forloop with index variableifrom0tosizeto initialize each grade:- Assign
grades[i] = i + 1as example values.
- Assign
- It should take
-
Implement a single method
calculateAverage:- Create a variable
suminitialized to0. - Use a
forloop with index variableifrom0tosizeto iterate over thegradesarray:- Add
grades[i]tosumin each iteration.
- Add
- Calculate the average as
sum * 1.0 / sizeto ensure adoubleresult. - Return the average.
- Create a variable
-
Implement a destructor:
- Use
delete[] gradesto release the memory allocated for the array. - Print
"Grades memory released."to indicate that the memory has been freed.
- Use
Example
GradesManager(5).calculateAverage() β 3.0
Solution
Thanks for your feedback!
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Awesome!
Completion rate improved to 3.13
Challenge: Managing Data with Constructors and Destructors
Swipe to show menu
Swipe to start coding
Imagine you are building a student grading system. You need to create a GradesManager class that manages a list of student grades.
Your task is to implement a constructor that initializes a dynamic array of grades and a single method that calculates the average grade. The destructor should release the allocated memory automatically.
-
Implement a constructor using initializer list syntax:
- It should take
sizeas a parameter. - Allocate a dynamic array of integers called
gradeswith the givensize. - Use a
forloop with index variableifrom0tosizeto initialize each grade:- Assign
grades[i] = i + 1as example values.
- Assign
- It should take
-
Implement a single method
calculateAverage:- Create a variable
suminitialized to0. - Use a
forloop with index variableifrom0tosizeto iterate over thegradesarray:- Add
grades[i]tosumin each iteration.
- Add
- Calculate the average as
sum * 1.0 / sizeto ensure adoubleresult. - Return the average.
- Create a variable
-
Implement a destructor:
- Use
delete[] gradesto release the memory allocated for the array. - Print
"Grades memory released."to indicate that the memory has been freed.
- Use
Example
GradesManager(5).calculateAverage() β 3.0
Solution
Thanks for your feedback!
single