Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Trace through the following program and write out the output of the program. Use

ID: 3721599 • Letter: T

Question

Trace through the following program and write out the output of the program. Use the number 10 for the requested input.

#include <iostream>

#include <cstdlib>

using namespace std;

class myclass {

int *p;

public:

myclass(int i);

~myclass();

int getval() { return *p; }

};

myclass::myclass(int i)

{

cout << "Allocating p ";

p = new int;

if(!p) {

    cout << "Allocation failure. ";

    exit(1); // exit program if out of memory

}

*p = i;

}

myclass::~myclass()

{

cout << "Freeing p ";

delete p;

}

// when this function is called, the copy constructor is called

void display(myclass ob)

{

cout << ob.getval() << ' ';

}

int main()

{

myclass a(10);

display(a);

return 0;

}

Explanation / Answer

myclass a(10);

above line will create an object of myclass and constructor will be called.
outpu: "Allocating p" will be displayed

now pointer p is pointing to memory that contains 10

display(a);
above line output:
   10

At the last constructor will be called.
Output:
   Freeing p


So, Output:

Allocating p
10
Freeing p

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote