top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is copy constructor?

+1 vote
462 views
What is copy constructor?
posted Dec 6, 2014 by Alwaz

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote

Copy Constructor is also a constructor whose main aim is to initialize the variable indirectly.
but here in copy constructor we are passing an object of the same class as a argument.
so, we can copy the value of that object into other one.

class sample
{
  int a;

  public:
    sample()
    {
        a = 10;
    }

    sample(&obj)
    {
        a = obj.a;
    }

    void show()
    {
        cout<<a;
    }
};

main()
{
  sample o1,o2;
  o1.show();
  o2.show();
}

in both it will print 10 on output screen;

answer Dec 8, 2014 by Chirag Gangdev
0 votes

Copy constructor is being used to create an object from an object of same class type. If a class has pointer variable as data member then copy constructor should be defined.
Default syntax to create an object as follows:

Class_Name(const Class_Name & obj)
{
// body of constructor
}

answer Dec 7, 2014 by Ganesh
...