Get premium membership and access questions with answers, video lessons as well as revision papers.

As you know, when an object is passed to a function, a copy of that object is made.Further, when that function returns, the copy's destructor...

      

As you know, when an object is passed to a function, a copy of that object is made.Further, when that function returns, the copy's destructor function is called.Keeping this in mind, what is wrong with the following program?
// This program contains an error.
#include
#include
using namespace std;
class dyna {
int *p;
public:
dyna(int i);
~dyna() { free(p); cout << "freeing \n"; }
int get() { return *p; }
};
dyna::dy*) malloc(sizeof(int));
if(!p) {
cout << "Allocation failure\";
exit(1);
}
*p = i;
}
// Return negative value of *ob.p
int neg(dyna ob)
{
retur.get();
}
int main()
{
dyna 0(-10);
cout << o.get() << "\n";
cout << neg(o) << "\n";
dyna o2(20);
cout << o2.get () << "\n";
cout << neg (o2)\n";
cout << o.get () << "\n";
cout << neg (o) << "\n";
return 0;
}

  

Answers


Davis
The memory used to hold the integer pointed to by p in object o that is usedcall neg() is free when the copy of o is destroyed when neg() terminates, even though this memory is still needed by o inside main()
Githiari answered the question on May 12, 2018 at 17:50


Next: If a queue dynamically allocates memory to hold the queue, explain the reason for that occurence and state whether in such a situation it...
Previous: other than the incorrect freeing of dynamically allocated memory, think of a situation in which it would be improper to return an object from a...

View More Computer Science Questions and Answers | Return to Questions Index


Learn High School English on YouTube

Related Questions