This program defines a class Example which has three member variables: a, b, and p. The constructor of the class initializes the pointer variable p to point to a dynamically allocated integer. The setExample() method sets the values of a, b, and *p to the passed arguments. The showExample() method displays the values of a, b, and *p.
The program creates an instance of Example named e1, sets its member variables, and then creates a second instance named e2 by copying e1. The values of e1 are then displayed using the showExample() method of e2.
Note that when the copy constructor is called, it performs a deep copy of the dynamically allocated integer pointed to by p by creating a new integer and copying the value of the original integer to it. This is necessary to ensure that each instance of the class has its own separate copy of the integer.
#include<iostream> using namespace std; class Example { public: int a; int b; int *p; Example() { p=new int; } Example(Example &d) { a = d.a; b = d.b; p = new int; *p = *(d.p); } void setExample(int x,int y,int z) { a=x; b=y; *p=z; } void showExample() { std::cout<<"value of a is : "<<a<<std::endl; std::cout<<"value of b is : "<<b<<std::endl; std::cout<<"value of *p is : "<<*p<<std::endl; } }; int main() { Example e1; e1.setExample(4,5,7); Example e2=e1; e2.showExample(); return 0; }To download raw file Click Here
value of a is : 4 value of b is : 5 value of *p is : 7
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions