Advertisement

Copy Constructor in C++

 In this article we are learning about copy constructor in C++ || Code with Abuzar 


What is copy constructor ?

https://abuzartec.blogspot.com/2021/06/copy-constructor-in-c.html

In object oriented programming copy constructor is a type of constructor which creating a new object as a copy object . Copy constructor is a standard way of copying object in C++ 

If copy constructor is not defined in a class , then the compiler itself define one . If the class has some pointer variable and have some dynamic memory allocation , then it is must to have a copy constructor .


Example  

#include <iostream>

using namespace std;

class Line {
   public:
      int getLength( void );
      Line( int len );             // simple constructor
      Line( const Line &obj);  // copy constructor
      ~Line();                     // destructor

   private:
      int *ptr;
};

// Member functions definitions including constructor
Line::Line(int len) {
   cout << "Normal constructor allocating ptr" << endl;
   
   // allocate memory for the pointer;
   ptr = new int;
   *ptr = len;
}

Line::Line(const Line &obj) {
   cout << "Copy constructor allocating ptr." << endl;
   ptr = new int;
   *ptr = *obj.ptr; // copy the value
}

Line::~Line(void) {
   cout << "Freeing memory!" << endl;
   delete ptr;
}

int Line::getLength( void ) {
   return *ptr;
}

void display(Line obj) {
   cout << "Length of line : " << obj.getLength() <<endl;
}

// Main function for the program
int main() {

   Line line1(10);

   Line line2 = line1; // This also calls copy constructor

   display(line1);
   display(line2);

   return 0;
}

When the above code is compiled and run it then the output is

Normal constructor allocating ptr
Copy constructor allocating ptr.
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Freeing memory!
Freeing memory!


Please ! Write comment if you find anything incorrect .

This article is contributed by Mohd Abuzar . If you like code with abuzar . or want to contribute with us so mail at - abuzar.abuzar.mohd325@gmail.com .



 

Post a Comment

0 Comments