Question
EXERCISES FOR C++ 1. Write a fragment of code to dynamically allocate memory for 1024 Point objects. What Point objects are instantiated for the array?
EXERCISES FOR C++
1. Write a fragment of code to dynamically allocate memory for 1024 Point objects. What Point objects are instantiated for the array? Assuming the Point class has a member function as follows: void draw ( ) const ;
Invoke the function draw for all Point objects in the array (you must use an extra pointer to do the task). Finally free the array memory. What will happen when the array memory de-allocation instruction is executed?
2. Assuming the following class declaration:
class Person {
private:
string name_;
int age_;
public:
Person ( );
Person ( string name, int age ) ;
bool Person::can_vote ( ) const;
} ;
Person::Person ( ) : age_ (0 ) { } // why don't we need to initialize string name_ ?
Person::Person ( string name, int age ) : name_ (name), age_ (age) { }
bool Person::can_vote ( ) const {
return (age_ >= 18) ;
}
3. Write a fragment of code that does the followings:
Declare an array of 512000 pointers to Person objects and initialized all pointer elemets to NULL.
Use a for loop to ask user to input name and age for each person, dynamically allocate a Person object for that person and assign it to the array. The for loop should be stopped when user enters "XYZ" for name.
Now use another for loop to count how many person can vote and show the output to the console.
Finally free the array of pointers. What will happen when delete person_list [i] is called?
Important note: In C++ it's ok to delete a NULL pointer. For example:
Person * p_person = NULL;
delete p_person ; // No problem here. C++ will not crash your program for trying to free a NULL pointer.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started