Important Introduction to Programming Short Questions
Chapter: 39
Question 1:
How is dynamic memory allocated in C++?
Answer:
Dynamic memory is allocated using the new operator, which returns a pointer to the allocated memory.
Chapter: 39
Question 2:
How do you deallocate memory allocated with new?
Answer:
You use the delete operator to deallocate memory, freeing it up for future use.
Chapter: 39
Question 3:
What is the syntax for allocating memory for an integer in C++?
Answer:
p = new int; where p is a pointer to an integer.
Chapter: 39
Question 4:
How do you allocate memory for an array of integers in C++?
Answer:
Use p = new int[size]; where size is the number of integers in the array.
Chapter: 39
Question 5:
How do you deallocate memory for an array allocated with new?
Answer:
Use delete[] p; where p is a pointer to the array.
Chapter: 39
Question 6:
What is the purpose of using const with references?
Answer:
The const keyword ensures that the referenced object cannot be modified within the function, only used.
Chapter: 39
Question 7:
How do you define a class with dynamically allocated memory in C++?
Answer:
Use a pointer as a data member and allocate memory in the constructor using the new operator based on input dimensions.
Chapter: 39
Question 8:
What is a common use case for dynamic memory allocation in classes?
Answer:
To handle variable-sized data structures like dynamic arrays or matrices that require memory allocation at runtime.
Chapter: 39
Question 9:
How would you declare a Matrix class that can handle variable sizes?
Answer:
Define a pointer to an integer, and allocate memory in the constructor based on row and column sizes provided.
Chapter: 39
Question 10:
What is the role of the new operator in dynamic memory management?
Answer:
The new operator allocates memory on the heap and returns a pointer to it, allowing for dynamic memory allocation.