In some C++ programs, it is desired that objects be deleted only using an object
ID: 3769820 • Letter: I
Question
In some C++ programs, it is desired that objects be deleted only using an objects manager. Consider the following definition of a C++ class called instruction(define in instruction.h) and an object manager class called objectManager. It is desired that the only non-member function that can delete objects of type instruction be the delete_obj method of an objectManager object. Thus, in the main function should generate a compile time error since the object a is deleted when it goes out of scope. The same holds for code that looks like this, also in main, since "delete p" will delete the dynamic object. What are the code changes needed to the class definition in instruction.h to make sure that only the delete.obj method of an ObjectManager object is able to delete objects of type instruction but no other method that is non-member of instruction can? Write your answer in the code boxes above.Explanation / Answer
We have to make ObjectManager as a friend class of instruction class.
Friend classes can access both private and protected members of a class. So, if we declare ObjectManager as a friend class of instruction, members of ObjectManager class can access any member of the instruction class.
You can do this by adding the below statement at the beginning of the instruction class:
friend class ObjectManager;
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.