Computer Programming
Java Programming
C Programming
C++ Programming

Why copy constructor will take reference object as argument?

Top Answer
User Avatar
Wiki User
Answered 2013-04-30 11:27:49

Because if it's not by reference, it's by value. To do that you make a copy, and to do that you call the copy constructor. But to do that, we need to make a new value, so we call the copy constructor, and so on...

(You would have infinite recursion because "to make a copy, you need to make a copy".)

User Avatar

Your Answer


Still Have Questions?

Related Questions

What is a copy constructor?

A copy constructor is a type of constructor which constructs the object of the class from another object of the same class. The copy constructor accepts a reference to its own class as a parameter. A valid copy constructor can be specified as, class A { ...... ...... public: A(&A); }

Why is the argument to copy constructor passed by reference?

It is not only passed by reference, but by constant reference. This ensures the reference's immutable members remain unaltered by the copy constructor. This makes perfect sense since we only wish to duplicate the reference's members, not mutate its members. If you think about it, the only way to pass by value would be to write a constructor overload to accept the value. But in order to pass an object by value you will automatically invoke the object's copy constructor in order to create a temporary object that can actually be passed to the constructor overload. The temporary copy will be destroyed when the constructor overload finishes, but you've essentially created two objects in order to create one object; that is an enormous overhead. Hence the reason we pass by reference in the first place. Passing a pointer to an existing instance will not invoke the copy constructor, but if you have a valid pointer you may as well pass by reference.

What is explicit copy constructor?

There is no such thing as an explicit copy constructor. Explicit constructors are required when we wish to prevent narrowing through implicit conversion of argument values, but a copy constructor's argument is a constant reference to an existing object of the same type, thus there is no implicit conversion and therefore no narrowing. That is, copying an object of type T or of a type derived from type T will always create a new object of type T. If we want to copy a type derived from a T, then we need to invoke that derived type's copy constructor, not the copy constructor for a T.

Why should be the formal argument of a copy constructor be a reference object Explain?

Not only must it be a reference it must be a constant reference. This makes sense since the copy constructor only needs to copy the members of the reference, not change them. The reason the object is passed by reference is simply that passing any object to a function by value will automatically copy that object as a temporary local variable for the function. Sometimes this is desirable to prevent the function from altering the original object, however in a copy constructor this would prove fatal to your class and your programs. If it were permitted, the object's copy constructor would end up calling itself recursively until the call stack was consumed, having never actually copied anything. As a general rule, all user-defined functions should accept a reference to an object, preferably a constant reference. Passing objects by value should be discouraged unless there is a genuine need to copy the object to prevent alterations to the original object, but only if there is no need to retain the copy (the copy falls from scope when the function returns). If an altered copy must be retained when the function returns, copy the object prior to calling the function, and pass the copy to the function by reference.

Why is object passed by reference to copy constructor?

Passing objects by value automatically creates a temporary copy of the object on the call stack. So even if it were possible to pass by value in a copy constructor, the call would not only allocate memory for the copy, it would call the copy constructor to initialise that memory, causing the copy constructor to iterate over and over until there was no more memory left in the call stack. Ultimately, your program crashes without ever having made a copy. Note that a copy constructor not only accepts objects by reference but by constant reference. This is because the copy constructor is only interested in copying the object's members, not in changing them. As a general rule, if an object can be passed to any function by constant reference then that is the way to go. If it is a non-constant reference, then the assumption is the object's immutable members will be altered by the function in some way. If you do not want any changes reflected in your object, then you must copy the object first, which is essentially what happens when you pass the object by value.

Why not sending arefrence to copy constructor will cause an infinite loop?

A copy constructor gets called any time an object needs to be copied. Unlike in some of the newer languages like Java, you can chose to pass objects either by reference or by value. When you pass by reference, only the address of the function is copied. However, if you pass by value, the whole object must be copied. In order to copy the object, the copy constructor will get called. If the copy constructor's parameter is not a reference, then the object will get passed by value. When the object gets passed by value, it needs to get copied so it will call the same copy constructor. Because the object is still being passed by value it'll call itself again to create a copy of itself. The copy constructor will continue to call itself until the stack overflows.

Can the parameter of the copy constructor be passed by value?

No. The parameter of the copy constructor is always passed by reference, specifically, a const reference to the class.Think about it. If it were passed by value, then the compiler would already know how to copy the object into the formal parameter, but the purpose of the copy constructor is to provide the code to copy the object, so its kind of a "cart before the horse" thing to think about call by value here.

Discrbe breifly about Copy constructor overloading?

A copy constructor usually refers to a constructor which takes an object, and returns a copy of that object. I can think of no way to overload the constructor without changing its functionality.

Why the copy constructor need of the reference variable?

The simple answer is that a constructor that accepts a reference to an instance of the same class of object is automatically identified as being the copy constructor for that class. That is; the copy constructor's unique signature differentiates it from all other constructors. Even if you do not declare a copy constructor explicitly, one is generated for you automatically by the compiler. Thus every class of object is guaranteed to have its own copy constructor, whether you declare one or not, uniquely identified by the fact it accepts a reference to an instance of the same class.The copy constructor is an essential and unique constructor. Whenever you call a function and pass arguments by value (whether those arguments are primitive data types or complex data types), those arguments must be copied. That is what it means to pass by value. So even if the function modifies those arguments in any way, those changes are local to the function -- only the copy is affected -- they do not affect the values that were actually passed by the caller. However, where the value is a complex data type like an object (an instance of a class), that object's copy constructor must be called, automatically, in order to make the copy. And the only way to identify which constructor is the copy constructor is by its signature: the one and only constructor that accepts a reference to the same class of object.The copy constructor has to accept a reference to the same class of object because we cannot pass by value. If it were even possible to pass by value to the copy constructor, the copy constructor would have to automatically copy that value, which would then result in the copy constructor recursively calling itself. The only possible outcome is that the program crashes when the call stack is consumed, having never made a single copy. For that reason, it is impossible to declare any constructor that accepts an instance of a class by value (in the absence of other arguments). The compiler simply will not allow it.When we pass an instance of an object by reference, that instance is not copied -- we are passing the instance itself, by reference. And since the copy constructor defines exactly how a copy is constructed from an instance, this is the only way it can be achieved.The only other way to copy an object is by passing a pointer to that object. But what do we do when the pointer is NULL? We cannot construct any meaningful copy of an object if there is no object to copy from. But, by calling the constructor, we must create an instance, meaningful or not. Passing by reference is the only way to guarantee that a meaningful copy of an object is constructed.It should be noted that references can also be NULL (if you inadvertently release a pointer to a reference, for instance), but any program containing a NULL reference is automatically deemed an invalid program. Any attempt to access the members of a NULL reference will result in a program crash. Even if you don't implicitly access those members, when a reference falls from scope a crash is inevitable as that will implicitly call the class destructor. So providing the program remains valid, it is safe to assume that all references are non-NULL.There are in fact two ways to declare the parameter of a copy constructor: by reference and by constant reference. The compiler-generated copy constructor passes by reference (and performs a member-wise, shallow copy of the instance). However, since a copy constructor must not alter the immutable members of that reference, it makes sense to declare the reference const when declaring your own copy constructor. You cannot declare both in the same class, but by using the const keyword, you assure yourself and the consumers of your class that your copy constructor implementation obeys this fundamental rule: that the immutable members of the reference will not be altered in any way.The only reason to actually declare and implement your own copy constructor is when you need to perform a deep copy of the members. That is, if your object contains pointer members, copying those pointers will result in two objects sharing the same memory. Sometimes this is acceptable. But if the class destructor releases those pointers, you have a problem: when one object falls from scope, all copies of that object are instantly deemed invalid. Thus you must deep-copy the pointers so that each instance owns its own memory. The only way to achieve that is to declare your own copy constructor which copies the memory being pointed at, not the pointer itself.copy constructor will copy the datamember values to another object by using the reference of that object that is from which object copy needs to be done

What is the purpose of a C plus plus constructor?

The constructor in C++ is a function that runs when an object is created. It is used to initialize the object. Types of constructors include default constructors (no arguments), copy constructor (one argument of same type as object), conversion constructors (one argument of some other type), and other constructors (all other cases). If you do not provide a default constructor, the object will not be initialized. If you do not provide a copy constructor, the compiler will blindly copy the attributes of the old object into the new object whenever a copy is made, such as in a function call with the object as an argument. This may or may not be safe, especially if any of the attributes are pointers, because that creates the situation of two pointers to the same region of memory. In that case, if that region of memory is an object, then when the object is destroyed, so will the pointed to object, and that will leave the original copied object in an invalid state, with its pointers referencing deleted memory.

What is casting in java and c plus plus?

Casting is the conversion of one type to another type, better known as a type cast. A class constructor that accepts one argument is a conversion constructor because it converts its argument to an object of the class. However, if the argument is of the same type as the class then it is known as a copy constructor.

What are multiple constructors?

Multiple constructors are overloaded versions of the class constructor. They are chosen based on their argument types. The default constructor takes no arguments. The copy constructor takes one argument of reference type to a const variable of the class. The conversion constructor takes one argument of different type than the copy constructor. Other constructors take two or more arguments and can be used for special initialization. Often, these other constructors can be built as one, using default values for arguments so, for instance, one of them could function as the default constructor if needed.

What is copy constructor in object oriented programming?

The purpose of constructor in object oriented programming is to initialize data. Likewise copy constructors are used to initialize an object with data from another object.

Why in copy constructor in c you use pass by reference?

C doesn't have classes and therefore has no copy constructors. In C++, however, copy constructors must pass by reference because pass by value creates a copy of the value, which invokes the copy constructor recursively. The end result is a call stack overflow and no copies will be made. Since copy constructors must not alter the original object, they must accept a constant reference rather than just a reference.

Why copy constructor uses call by reference?

When you pass any object or primitive data type by value, the function must make a temporary copy of the value which is local to the function, and falls from scope when the function returns. Since the function must call the object's copy constructor to make the copy, you cannot pass the object by value to its own copy constructor. If you could, you'd invoke an infinite recursion upon the copy constructor, passing the same value over and over until the call stack is consumed, having never made a single copy of the value. Copy constructors must not only pass by reference, but by constant reference. Any function that accepts a constant reference is the preferred choice because it guarantees the object's immutable members will not be altered by the function call. The next best option is call by reference when you expect changes to be reflected in the original object, or call by value when you don't.

What is constructor invocation in c plus plus?

Whenever a new object is instantiated, the appropriate class constructor for that object is invoked automatically. At compile time, argument-dependent lookup is used to determined which specific constructor to invoke. When passing objects to functions by value, the class copy constructor is invoked. If there is no copy constructor for the class, objects of this class cannot be passed by value. When returning objects from functions by value, the class move constructor is invoked. If there is no move constructor for the class, the class copy constructor is invoked instead. If neither exists, objects of this class cannot be returned by value.

Why do you use reference to an object in a copy constructor?

The copy constructor is a special type of constructor. It is identified by the fact that it always accepts a reference to an instance of the same class via its first argument. If there are any additional arguments in the copy constructor, they must have default values. If default values are not provided, the constructor cannot be regarded as a copy constructor. The purpose of the copy constructor is to make an exact copy of an existing object. The reason we must pass the existing object by reference is simply because there is no other way to do it. The compiler won't allow you to pass the exiting object by value because whenever you pass an object by value you automatically invoke the object's copy constructor. Thus the copy constructor would recursively invoke itself. The only other option would be to pass the instance by pointer, but since pointers may be NULL, this is less efficient than passing by reference. References can never be NULL; they must always refer to an existing instance. A NULL reference would result in an invalid program. So although it is possible to construct a copy from a pointer, the extra checks required to ensure the pointer is non-NULL make it less efficient. The following example should demonstrate the difference more clearly: #include<iostream> class foo { int m_data; public: foo(): m_data(0) {} // default constructor foo(const foo& f): m_data(f.m_data) {} // copy constructor foo(const foo* f): m_data(f?f->m_data:0) {} // alternate constructor }; int main() { foo a; // invokes the default constructor foo b(a); // invokes the copy constructor foo c(&b); // invokes the alternate constructor } Since the purpose of the copy constructor is to make a copy of an existing object without altering the existing object, it makes sense to pass a const reference (as shown above), thus assuring the caller that the existing instance's immutable members will not change. Note also that when passing instances of foo by value, the copy constructor is always invoked, never the alternate constructor. As far as the compiler is concerned, the alternate constructor is just another constructor like any other. But since it serves no purpose that isn't already fulfilled by the copy constructor, there's no point in declaring it; it is surplus to requirements. Note also that even if you do not declare your own copy constructor, the compiler will automaticallly generate one for you. However, the compiler-generated copy constructor will perform a member-wise copy (a shallow copy). In many cases this is adequate. But if your class encapsulates unshared memory then you must provide your own copy constructor to ensure that that memory is deep copied. If not, both instances will end up sharing the same memory. This will prove disasterous when one instance is deleted, because the remaining instance(s) would end up pointing at memory that is no longer valid. By deep copying the memory, you ensure that each instance points to its own copy of the memory.

Advantage of copy constructor?

Without a copy constructor the only way to copy an object would be to instantiate a new object (or use an existing object) and then assign another object's value to it. However, it would be very odd indeed to have a copy assignment operator without a matching copy constructor. If you have one, you must have both. If you do not need to copy an object of a particular class, however, you can simply delete both the copy constructor and the copy assigment operator for that class. Any attempt to copy or copy assign would then result in a compile-time error.

What is Constructor in C plus plus?

A constructor is a special class method that instantiates an object of the class. All objects must have at least two constructors, one of which must be a copy constructor. Even if you do not explicitly declare a copy constructor, one is generated for you with public access by the compiler. The purpose of the copy constructor is to instantiate new objects from existing objects. Even if you never explicitly call the copy constructor, it is automatically called whenever you pass an object to a function by value, as the object must be copied. If you do not declare any constructors, then both the copy constructor and the default constructor are generated for you. The default constructor is a constructor that accepts no parameters, or that is declared with all default parameters. Although the compiler will generate default and copy constructors for you, it is always recommended that you declare your own constructors, thus ensuring your object members are always correctly initialised and valid. An uninitialised object is a potential time-bomb. Constructors are not functions; they do not return any value, not even void. The assignment operator (which does return a value) is not a constructor; it is used to initialise an existing object from another existing object -- it does not instantiate a new object. Constructors are called whenever you instantiate a reference to an object, or allocate memory to an object using the new operator, or copy a new object from an existing object. All constructors have the same name as the class itself. Construction overloads can be differentiated by their signature (the number and type of parameters they accept). The copy constructor is signified by the fact its only parameter is a constant reference to an object of the same class. class Object { public: Object(); // Default constructor (no parameters) Object(const Object& object); // Copy constructor Object(int x); // Overloaded constructor } As well as constructors, it is recommended you also declare your own assignment operator and destructor. Even if the compiler-generated versions are adequate for your needs, it costs nothing but a little time to declare your own. But if your class allocates dynamic memory on the heap, you must include code in the constructors, destructor and assignment operator to ensure that memory is correctly initialised and released, and that self-references are correctly accounted for; the compiler-generated methods will not do it for you.

What are the properties of a constructor function in c plus plus?

A constructor is not a function. A function is a type, as specified by its return type, and must return a value of that type unless the type is void. A constructor does not return anything, not even void. The purpose of a constructor is to both allocate and initialise memory for an object of the type being constructed. If a valid object cannot be constructed for any reason, the constructor must throw an exception. If the object's class has no data members (attributes), the class does not require a constructor. This is typically the case for most abstract data types and base classes which are used purely as interfaces. Constructors differ from functions in that all constructors have an initialisation section that is used specifically to initialise non-static data members. The body of the constructor is rarely used except to perform initialisations that cannot be more easily performed by the initialisation section. A class may have more than one constructor to provide alternative methods of construction based upon the number and type of arguments supplied (if any). When no arguments are required or all arguments have default values then the constructor is known as the default constructor. If the constructor has only one argument the constructor is known as a conversion constructor (because the argument is converted to an object of the class). However, if the constructor argument is a constant reference to an object of the same class, then it is known as a copy constructor, and when the constructor argument is an rvalue reference, it is known as a move constructor. If copy and/or move constructors are provided for a class, the equivalent assignment operators should also be provided for that class. All other constructors are known as user-defined constructors.

Compare call by value and call by reference with an example?

Call by value passes a copy of the argument into the function parameter while call by reference passes the argument itself. Call by value automatically copies the argument, thus if the argument is a complex object, the object's copy constructor will be called. The following example demonstrates the difference. Note that call by value calls the copy constructor but call by reference does not. Since call by value works on a copy of the object, the original object is left unaffected. However call by reference can mutate the object. #include <iostream> class object { public: object(int data):m_data(data){} object(const object& rhs):m_data(rhs.m_data){std::cout << "Copying" << std::endl;} int get_data()const{return(m_data);} void set_data(int data){m_data=data;} private: int m_data; }; void byVal(object o) { o.set_data(1); } int byRef(object& o) { o.set_data(1); } int main{ object a(0); std::cout << "a is " << a.get_data() << std::endl; std::cout << "Calling by value" << std::endl; byValue(a); std::cout << "a is " << a.get_data() << std::endl; std::cout << "Calling by reference" << std::endl; byRef(a); std::cout << "a is " << a.get_data() << std::endl; return( 0 ); } Output: a is 0 Calling by value Copying a is 0 Calling by reference a is 1

Which key word is used as constructor in c plus plus?

There is no specific keyword for a constructor in C++. Simply define and declare a method of the class with the same name as the class and it will be a constructor. A constructor with no arguments is the default constructor, a constructor with one argument of class type is the copy constructor, and a constructor with one argument of some other type is the conversion constructor. You can provide other overloaded constructors if you want.

What is constructor and discuss different types of constructor with syntax and examples?

A constructor is a class method which initialises an object of the class at the point of instantiation. Specifically, it initialises the base classes (if any) and the non-static data members (if any). Constructors also play a central role in the resource acquisition is initialisation (RAII) paradigm. Objects which have a natural default value have a default constructor. The default constructor is a constructor that has no arguments or where all arguments have default values. Objects which can be copied have a copy constructor. The copy constructor has just one non-default argument, a const l-value reference of the same type as the class. Objects which can be moved have a move constructor. The move constructor has just one non-default argument, a modifiable r-value reference of the same type as the class. All other constructors that have only one argument of a type other than the class itself are known as conversion constructors. Constructors can also have more than one argument. No specific name is given to these constructors. Other than physical memory constraints, there is no limit to the number of constructors that may be defined for a class.

Use of copy constructor?

The purpose of the copy constructor is to construct a new object from an existing object of the same class. When passing objects to functions by value, the copy constructor is also called because a temporary object must be created (passing by reference or pointer does not call any constructor). The copy constructor is also used when assigning an existing object to a new object. Note that the assignment operator is only used when assigning an existing object to another existing object.Consider the following example which demonstrates where and when the copy constructor is called:#include class Object{public:Object():data(0){ printf("Default constructed at 0x%.8x with data %d\n",this,data); };Object(const Object& object):data({ printf("Copy constructed at 0x%.8x with data %d\n",this,data); }Object& operator=(const Object& object){ printf("Assign at 0x%.8x with data %d from 0x%.8x with data %d\n",this,data,&object,;; return(*this);}~Object(){printf("Destroy 0x%.8x with data %d\n",this,data);}void SetData(int i){data=i; printf("Mutate 0x%.8x with data %d\n",this,data);}private:int data;};void ByVal(const Object object ){return;}void ByRef(const Object& object ){return;}void ByPtr(const Object* object ){return;}int main(){printf("Calling default constructor:\n");Object object1;object1.SetData(1);printf("Calling copy constructor:\n");Object object2(object1);object2.SetData(2);printf("Calling copy constructor:\n");Object object3 = object2;object3.SetData(3);printf("Calling assignment operator:\n");object2 = object1;printf("Calling ByVal:\n");ByVal(object1);printf("Calling ByRef:\n");ByRef(object2);printf("Calling ByPtr:\n");ByPtr(&object3);printf("Exiting:\n");return(0);}Output:Calling default constructor:Default constructed at 0x0022fd60 with data 0Mutate 0x0022fd60 with data 1Calling copy constructor:Copy constructed at 0x0022fd54 with data 1Mutate 0x0022fd54 with data 2Calling copy constructor:Copy constructed at 0x0022fd48 with data 2Mutate 0x0022fd48 with data 3Calling assignment operator:Assign at 0x0022fd54 with data 2 from 0x0022fd60 with data 1Calling ByVal:Copy constructed at 0x0022fc54 with data 1Destroy 0x0022fc54 with data 1Calling ByRef:Calling ByPtr:Exiting:Destroy 0x0022fd48 with data 3Destroy 0x0022fd54 with data 1Destroy 0x0022fd60 with data 1Note that all classes have a default constructor, a copy constructor, an assignment operator and a destructor, even if you do not declare them (the compiler generates them for you). However, if you declare any constructor, including the copy constructor, the default constructor is not generated for you unless you declare one yourself. But you cannot have a class that only has a copy constructor as it would be impossible to instantiate the objects you wished to copy from.

How do you pass an array to a copy constructor in c plus plus?

You cannot pass an array to a copy constructor. A copy constructor only accepts a constant reference to the object being copied, which must be of the same class as the object being constructed. An array is not an object of any class, and therefore cannot be used in any copy constructor. Although you cannot pass an array to a copy constructor, you can pass an array to a non-trivial constructor. It is not recommended, however, as there's no way to bounds-check the array being passed, which could result in an invalid object being created -- which is never a good thing. Even if you pass the array and its dimension(s) to the constructor, how can you guarantee those dimensions are valid for the array being passed? And what will you do if they are invalid? After all, you cannot veto the construction of an object once you've called its class constructor. Not knowing why you want to pass an array to a copy constructor, or how you intend to initialise the members via an array, makes it somewhat difficult to determine the best solution for you. However, I would consider using mutators instead of constructors. There's still the problem with bounds-checking but at least you won't have to deal with it during the object's construction.