COPY CONSTRUCTOR | OOPS

Ad

COPY CONSTRUCTOR | OOPS

COPY CONSTRUCTOR | OOPS
A Copy constructor is an overloaded constructor used to declare and initialize an object from another object.

Copy Constructor is of two types:

  • Default Copy constructor: The compiler defines the default copy constructor. If the user defines no copy constructor, the compiler supplies its constructor.
  • User-Defined constructor: The programmer defines the user-defined constructor.



CODE: 

#include <iostream>

using namespace std;

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();

        Student s2(s1);

        s2.name[0] = 'x';
        s1.display();
        s2.display();
        /*
        name[3] = 'e';
        Student s2(24, name);
        s2.display();

        s1.display();
        */

}

  • We should always create our own copy constructor (with deep copy in it) just to avoid shallow copy, as the inbuild copy constructor carries shallow copy while copying the objects. (Click here to read more about Deep Copy and Shallow copy)
  • While making a copy constructor, we should always, pass the object by reference, as if we do not pass the object by reference, we will get into a recursive loop of copy constructor.
    • Student(Student &s)
  • To avoid illegal changes to our object, we should make the object reference as constant, so that we cannot do any changes to the passed object.
    • Student(Student const &s)

0 Response to "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