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
size
as a parameter. - Allocate a dynamic array of integers called
grades
with the givensize
. - Use a
for
loop with index variablei
from0
tosize
to initialize each grade:- Assign
grades[i] = i + 1
as example values.
- Assign
- It should take
-
Implement a single method
calculateAverage
:- Create a variable
sum
initialized to0
. - Use a
for
loop with index variablei
from0
tosize
to iterate over thegrades
array:- Add
grades[i]
tosum
in each iteration.
- Add
- Calculate the average as
sum * 1.0 / size
to ensure adouble
result. - Return the average.
- Create a variable
-
Implement a destructor:
- Use
delete[] grades
to 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
solution.cpp
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
size
as a parameter. - Allocate a dynamic array of integers called
grades
with the givensize
. - Use a
for
loop with index variablei
from0
tosize
to initialize each grade:- Assign
grades[i] = i + 1
as example values.
- Assign
- It should take
-
Implement a single method
calculateAverage
:- Create a variable
sum
initialized to0
. - Use a
for
loop with index variablei
from0
tosize
to iterate over thegrades
array:- Add
grades[i]
tosum
in each iteration.
- Add
- Calculate the average as
sum * 1.0 / size
to ensure adouble
result. - Return the average.
- Create a variable
-
Implement a destructor:
- Use
delete[] grades
to 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
solution.cpp
Thanks for your feedback!
single