Need helps on C++ attach. Thanks Pointers with classes a) A user-defined class n
ID: 3688555 • Letter: N
Question
Need helps on C++ attach. Thanks
Pointers with classes a) A user-defined class named Timer has a constructor that takes two integer parameters to initialize hour and minute data members. Write a single C++ statement to create an object of the Timer class using dynamic memory allocation and assign it to a pointer variable named timePt r. It should call the constructor with two parameters. Use values of 10 and 20 for hour and minute respectively. b) Write the definition for a function named randArray that takes a single integer argument, n, and returns a dynamically allocated array of n pseudo-random integers. You may assume the pseudo-random number generator has been previously declared and seeded, (i.e. you do not need srand(time(0)) or an include.) c) Now write C++ statements to call the randAr ray function to construct a 100 element array, then print the array values to the display (one per line) and delete the dynamically allocated array.Explanation / Answer
Ok. Lets answer your question part by part.
a) We need to create a dynamically allocated object of Timer class, and assign it to a pointer variable timePtr.
As we are going to create an object of timer class, so timePtr will be a pointer of type timer class. Hence, left side of the statement will be as follows.
Timer* timePtr
Now, to dynamically create an object, we use new operator in C++. And at last, we need to call the constructor to create the object. So, the full statement will be as follows:
Timer* timePtr = new Timer (10, 20);
b) We need to write function definition for taking single argument n as input and return a dynamically allocated array of pseudo-random integers. It will be as follows:
int* randArray (int n) {
int* randomArray = new int[n]; //Allocate n ints and save ptr in randomArray.
for (int i=0; i<n; i++) {
randomArray[i] = rand(); //Initialize elements with pseudo-random values
}
return randomArray; //return the address of the first element i.e. starting of array
}
c) Here we need to call the randArray function and print the elements values.
int* randomArray = randArray(100); //call randArray function to get a random array of 100 elements
for (int i=0; i<100; i++) {
cout << randomArray[i] << endl; //Display the elements, one per line
}
delete[] randomArray; //use array delete i.e. delete[], not just delete to deallocate the array
randomArray = 0; //set randomArray ptr to null, use nullptr if using c++11
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.