Deep copy and Shallow copy | CONSTRUCTOR | OOPS

Ad

Deep copy and Shallow copy | CONSTRUCTOR | OOPS

Deep copy and Shallow copy | CONSTRUCTOR | OOPS

CODE:

#include <iostream>
using namespace std;
#include "Student.cpp"

class Student {
        int age;

        public :

        char *name;
       
        Student(int age, char *name) {
                this -> age = age;
                // Shallow copy
                // this -> name = name;
       
                // Deep copy
                this -> name = new char[strlen(name) + 1];
                strcpy(this -> name, name);
       
        }

        // Copy constructor
        Student(Student const &s) {
                this -> age = s.age;
                // this -> name = s.name;              
                // Shallow Copy
       
                // Deep copy
                this -> name = new char[strlen(s.name) + 1];
                strcpy(this -> name, s.name);
        }

        void display() {
                cout << name << " " << age << endl;
        }
};

int main() {
        char name[] = "abcd";
        Student s1(20, name);
        s1.display();

        name[3] = 'e';
        Student s2(24, name);
        s2.display();

        s1.display();


}

SHALLOW COPY

Student ( int age, char *name )
{
        this -> age = age;

        // This is Shallow Copy
       this -> name = name ;
}

In shallow copy, we are assigning the same memory of the main function's name to the S1's name, due to which any changes made in the main function's name will be reflected in the S1's name, and all the objects would be pointing to the same name char array which will be main function's name.





DEEP COPY

Student ( int age, char *name )
{
        this -> age = age;

        // This is Deep Copy
       this -> name = new char[ strlen(name) + 1 ] ;
       strcpy ( this -> name , name ) ;
}


In deep copy, we are creating a memory of size same as the main function's name's size for S1's name. After creating the memory block, we are copying the main function's name to S1's name, due to which any changes made in the main function's name will not be reflected in the S1's name, and all the objects would have a unique address for name char array.


NOTE: Default Copy constructor and Copy assignment operator uses shallow copy.

0 Response to "Deep copy and Shallow copy | CONSTRUCTOR | OOPS"

Post a Comment

If you have any doubts, please let me know...

Ads Atas Artikel

Ads Center 1

Ads Center 2

Ads Center 3