In C++
PART 1: Write a constructor for a class data type named
Test that has the following two member
variables:
double arr*; int size;
The constructor should take one argument for the size and then dynamically allocate an array of that size.
PART 2: Write a destructor for the Test class.
Constructor: A member function of a class with same name as class which usually deals with creating memory and initialising the the data members of the class. constructor will be called by compiler to create an object
Destructor: A destructor a member function of a class which deletes the allocated memory for the class. once the object goes out of scope destructor will be called by compiler
To create dynamic memory we can use new keyword and to delete memory allocated by new we can use delete keyword. To delete an array of memory use delete[]
CODE:
#include <iostream>
//part 1
// class data type named Test
class Test{
//that has the following two member variables:
double *arr;
int size;
//Write a constructor for a class - should be public to create objects
public:
//The constructor should take one argument for the size and then dynamically allocate an array of that size.
Test(int s){
//std::cout<<"Constructor called\n";
size=s;
arr=new double[size];
}
//part 2
//Write a destructor for the Test class
~Test(){
//std::cout<<"Destructor called\n";
delete[] arr;
}
};
int main() {
//Sample Object t creation
Test t(10);
}
Note: Un comment the std::cout statements to understand the automatic behaviour of object management in c++
Get Answers For Free
Most questions answered within 1 hours.