Interview Questions   Tutorials   Discussions   Programs   Videos   

C++ - What is copy constructor?




355
views
asked marvit August 19, 2014 09:55 AM  

What is copy constructor?


           

1 Answers



 
answered By bhjahnavi   0  
The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously.
consider the following example for copy constructor
/* example program for copy constructor*/
#include <iostream>

using namespace std;

class Line
{
  public:
   int getLength( void );
   Line( int len );       
   Line( const Line &obj); 
   ~Line();          

  private:
   int *ptr;
};


Line::Line(int len)
{
  cout << "Normal constructor allocating ptr" << endl;
  ptr = new int;
  *ptr = len;
}

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

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;
}
int main( )
{
  Line line(10);

  display(line);

  return 0;
}
flag   
   add comment

Your answer

Join with account you already have

FF

Preview


Ready to start your tutorial with us? That's great! Send us an email and we will get back to you as soon as possible!

Alert