207k views
0 votes
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 timePtr. 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 randArray function to construct a 100 element array, then print the array values to the display (one per line) and delete the dynamically allocated array.

User Raphael K
by
4.7k points

1 Answer

2 votes

Answer:

Check the explanation

Step-by-step explanation:

a) there is a need to create an allocated object of dynamic ability for the 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 create an object in a dynamic way, 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)

//c++ code : a:

#include <iostream>

using namespace std;

class Timer

{

public:

int hr;

int minute;

Timer(int h,int min)

{

h=h+min/60;

min=min%60;

hr=h;

minute=min;

}

};

int main()

{

Timer *t=new Timer(10,20);

cout<<"Time : "<<t->hr<<" hr :"<<t->minute<<" min"<<endl;

return 0;

}

c)

//c++ code for b, c:

#include <iostream>

#include <stdlib.h>

#include <time.h>

using namespace std;

int* randfun_alloc(int n)

{

srand (time(NULL));

int *arr=new int[n];

for(int i=0;i<n;i++)

arr[i]=rand()%1000;

return arr;

}

int main()

{

int n;

cin>>n;

int *arr =randfun_alloc(n);

for(int i=0;i<n;i++)

cout<<arr[i]<<" ";

cout<<endl;

delete[] arr;//delete the allocated array

return 0;

}

Documents: bash Konsole File Edit View Bookmarks Settings Help raushan-HP-2000-Notebook-PC /Documents > g++ randarr.c

User Ashwin Praveen
by
4.4k points