Answer to Question #180481 in C++ for Shashank Shekhar Singh

Question #180481

. Create a class Number with a pointer as a data data member of integer type. Write user defined copy constructor to the class and implement the deep copy for the Number class objects. So when a new object is created from an old object of the Number class, pointer data member can point different memory block.


1
Expert's answer
2021-04-13T02:00:15-0400
#include<iostream>
using namespace std;
  
class Number
{
    int *ptr;
public:
    Number (int i = 0)      { ptr = new int(i); }
    void setValue (int i) { *ptr = i; }
    void print()          { cout << *ptr << endl; }
    Number & operator = (const Number &t);
};
  
Number & Number::operator = (const Number &t)
{
   // Check for self assignment
   if(this != &t)
     *ptr = *(t.ptr);
  
   return *this;
}
  
int main()
{
    Number t1(5);
    Number t2;
    t2 = t1;
    t1.setValue(10);
    t2.print();
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

Assignment Expert
12.04.21, 18:49

Dear Venkat, please use panel for submitting new questions

Venkat
12.04.21, 18:48

Define a class Employee with data members as name, emp_id, age. Write a program to write the data of three employee’s using class object. Read the records of the employee and print them to console.

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS