At the end of the function below, write the necessary statements to deallocate m
ID: 3917073 • Letter: A
Question
At the end of the function below, write the necessary statements to deallocate memory, to avoid a memory leak.
Void foo()
{
int a[5];
int *b = new int;
int *c = new int[5];
}
Write each function in the Movie class below. Each Movie object has a title (stored as a string) and a list of actors (stored in a dynamically allocated array).
class Movie{
string title;
int numActors; // numActors stores the size of the array
string *actors;
public;
// Constructor: Set the title to t. If n > 0, set numActors to n
// and dynamically allocate an array of size n.
// otherwise set actors = NULL.
Movie(string t, int n){
}
// If index I is valid (0 <= i < numActors),
// Set the actor at index I to a. otherwise do nothing.
String setActor(string a, int i){
}
// Returns the title (This function has been written for you)
string getTitle(){
return title;
}
3. Continuation of Movie class.
If you declare the getTitle function as a const, will the program will compile? Explain why or why not?
4. Write the Big Three for the Movie class. You should do whatever memory deallocation is necessary to avoid a memory leak.
// Destructor
~Movie(){
}
// Copy constructor
Movie(const Movie &orig){
}
//Assignment operator (don’t forget the self-assignment test)
Movie& operator=(const Movie &rhs){
}
5. Declare a Movie object, using the constructor that you wrote (pass any parameters of the correct type). Then print the title (call the object’s getTitle function to get its title).
Explanation / Answer
please give thumbs up, thanks
#include<iostream>
using namespace std;
class Movie
{
string title;
int numActors; // numActors stores the size of the array
string *actors;
public:
// Constructor: Set the title to t. If n > 0, set numActors to n
// and dynamically allocate an array of size n.
// otherwise set actors = NULL.
Movie(string t, int n){
title=t;
numActors=n;
actors=new string[numActors];
}
// If index I is valid (0 <= i < numActors),
// Set the actor at index I to a. otherwise do nothing.
string setActor(string a, int i){
if(i<numActors)
{
actors[i]=a;
}
}
// Returns the title (This function has been written for you)
string getTitle(){
return title;
}
//q4
~Movie()
{
delete []actors;
}
Movie(const Movie &orig){
title=orig.title;
numActors=orig.numActors;
actors=orig.actors;
}
Movie& operator=(const Movie &rhs){
title=rhs.title;
numActors=rhs.numActors;
actors=rhs.actors;
}
};
int main()
{
//question no 5's solution
Movie M=Movie("Anaconda",10);
cout<<M.getTitle();
Movie C=M;
cout<<C.getTitle();
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.