Create a class that has a constructor and a destructor In th

Create a class that has a constructor and a destructor. In the constructor print \"Object Created\". In the destructor print \"Object Destroyed\". First create the object locally. Second, create the object dynamically. Then delete it. Third, create the object with a smart pointer, then reset it Use the debugger to see when the destructor and constructor are called. Then answer these questions: When did the destructor and constructor get called from the local created object? When did the destructor and constructor get called from the dynamically created object? When did the destructor and constructor get called from the smart pointer created object?

Solution

#include<iostream>
#include<stdio.h>
using namespace std;
class Demo
{
//Static data member to keep track of object
static int c;
public:
//Default constructor displays object status
Demo()
{
cout<<\"\ Object \"<<++c<<\" Created\";
}
//Destructor displays object status
~Demo()
{
cout<<\"\ Object \"<<c++<<\" Destroyed\"<<endl;
}
};
//Initializes the static data member
int Demo :: c = 0;
int main()
{
//Local scope for object
{
cout<<\"\ Local Object\"<<endl;
Demo d1;
}
cout<<\"\ Dynamic Object \"<<endl;
Demo *d2 = new Demo();
delete d2;

cout<<\"\ Smart Pointer \"<<endl;
{
Demo *d3(new Demo());
}
Demo *d4(new Demo());
getchar();
}

Output:

Local Object

Object 1 Created
Object 1 Destroyed

Dynamic Object

Object 3 Created
Object 3 Destroyed

Smart Pointer

Object 5 Created
Object 6 Created

Create a class that has a constructor and a destructor. In the constructor print \
Create a class that has a constructor and a destructor. In the constructor print \

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site