You are here:

C++/Copy constructor

Advertisement


Question
1) what is importance of const. reference object of same class type in copy constructor

2) Why do we use reference of class instead of simple pass by value.

3) Again one query why dont we use pass by pointer in copy constructor  

Answer
A copy constructor is used to make a copy of an object. The copy constructor would be used in the following scenarios:

class Person { /* ....  person members ... */ } ;

Person some_function( Person a_person )
{
     // this function takes its parameter by value; ie. it gets a copy of the argument
     // the copy constructor of the person is used to make this copy

     Person copy_of_person( a_person ) ;
     // the copy constructor of the person is used to make this copy

     return  copy_of_person ;
     // an object is returned by the function.
     // the copy constructor of the person is (conceptually) used to make this copy

}

The copy constructor can be invoked with a single argument that is a reference to the object being copied.

It is a const reference; logically making a copy of something should not change the original object.

It is a reference, because a value parameter would require making a copy, which would invoke the copy constructor, which would make a copy of its value parameter, which would invoke the copy constructor,
which ...

You can write a constructor which takes a pointer as the parameter, but it would not be a copy constructor. The copy of a pointer is a copy of an address, it does not make another object of the type pointed to.  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.