answersLogoWhite

0


Best Answer

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

Wiki User

11y ago
This answer is:
User Avatar
More answers
User Avatar

Wiki User

9y ago

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.

This answer is:
User Avatar

User Avatar

Wiki User

10y ago

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.

This answer is:
User Avatar

User Avatar

Wiki User

11y ago

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.

This answer is:
User Avatar

User Avatar

Wiki User

12y ago

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.

This answer is:
User Avatar

User Avatar

Wiki User

11y ago

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.

This answer is:
User Avatar

User Avatar

Wiki User

11y ago

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.

This answer is:
User Avatar

User Avatar

Wiki User

11y ago

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

This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: Why in copy constructor in c you use pass by reference?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Continue Learning about Engineering

What is the method of constructor overloading in c plus plus?

Constructor overloading, just like any function's overloading, is where more than one configuration of parameters exists for the function. Based on the number and type of the parameters, different versions of the function can be resolved by the linker. This is typically used in the constructor as the default constructor (no parameters), the copy constructor (one reference parameter of the same type as the class), and the conversion constructor (any other combination of parameters).


What is a constructoris it mandatory to use constructor in a class?

You always should define default constructor for your class. You must also define a copy constructor for your class if there are any pointers in the class. While it is not mandatory, failure to provide a default constructor can result in bad behavior, and failure to provide a copy constructor when you have pointers in the class will result in bad behavior. For example, without a default constructor, the compiler will not fully initialize the attributes of the class. It will initialize the virtual function table, and call base class constructors, but that is all - the attributes could be random garbage. For another example, without a copy constructor, the compiler will generate one that simply makes a bit wise copy of the attributes. If these attributes contain pointers, then you have two pointers to the same object, not necessarily a good thing, especially if one of them get "deleted".


What are the 6 ways to use this keyword?

"Java This keyword" is a reference to the current object, it is very helpful when you need to refer an instance of a particular Object from its available methods or using it's constructor, also "this" keyword helps us to avoid naming conflicts.The following are different ways to use java this keyword1) Using with instance variable2) Using with Constructor3) Pass / Return current instanceUsing with instance variableUsing this keyword inside a method or constructor it will use instance variable instead of local variable, in the absence of this keyword it will use local variableUsing with instance variableUsing this keyword inside a method or constructor it will use instance variable instead of local variable, in the absence of this keyword it will use local variableUsing with ConstructorUsing this keyword inside constructor like followingthis("Sony", 20); it will call the constructor having same parameter


Which situation constructor is used?

Constructor is necessary when you are about to use instance of a class.


What are the advantages of constructor and destructor?

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.

Related questions

What is meant by copy constructor overloading?

It is meaningless. Copy constructors cannot be overloaded. You either use the compiler-generated default copy constructor or you define your own. Either way, there can only ever be one copy constructor. The purpose of the copy constructor is to construct a new instance of a class (a new object) from an existing instance of the same class (an existing object). By default, the new object's members will be a bitwise copy (a shallow copy) of the existing object's members. If the class acquires a resource through a member pointer, a user-defined copy constructor must be provided in order to perform a deep copy of that pointer, otherwise you end up with two objects sharing the same resource. This problem does not exist when using smart pointers or resource handles rather than raw pointers.


Why call by reference is more prefareble than call by value?

Pass by reference is preferable when we need to pass an object that is too large to fit into a CPU register. Typically this means any object of a type larger than a pointer. When we pass large objects by value, a new object is copy constructed from the object's value, and that can have a serious impact on performance. Passing by reference ensures that no copy is made; we're simply passing the object's memory address, which is guaranteed to fit in a CPU register. Ideally we should pass by constant reference because users do not expect functions to have side-effects. If a function needs to alter the value of its argument, then it should use the pass by value semantic. If we need to return the modified value back to the caller, it should use the return value. With appropriate move semantics, returning objects by value has minimal impact and eliminates all side-effects: class X { public: X (const X&amp;); // copy construct X&amp; operator= (const X&amp;); // copy assign X (X&amp;&amp;); // move construct X&amp; operator= (X&amp;&amp;); // move assign // ... }; X use (X obj) { // pass by value (invokes copy constructor) // modify obj... return obj; // return by value (invokes move constructor) } X x1; x1 = use (x1); Passing by non-const reference to achieve the same end can have a (slight) performance advantage, however passing by value ensures the caller is wholly responsible for any side-effects and not the function. If a function has side-effects, we need to know what they are, but we don't always have access to the source code, so passing by value or by const reference ensures there aren't any side-effects.


What is the method of constructor overloading in c plus plus?

Constructor overloading, just like any function's overloading, is where more than one configuration of parameters exists for the function. Based on the number and type of the parameters, different versions of the function can be resolved by the linker. This is typically used in the constructor as the default constructor (no parameters), the copy constructor (one reference parameter of the same type as the class), and the conversion constructor (any other combination of parameters).


What is a constructoris it mandatory to use constructor in a class?

You always should define default constructor for your class. You must also define a copy constructor for your class if there are any pointers in the class. While it is not mandatory, failure to provide a default constructor can result in bad behavior, and failure to provide a copy constructor when you have pointers in the class will result in bad behavior. For example, without a default constructor, the compiler will not fully initialize the attributes of the class. It will initialize the virtual function table, and call base class constructors, but that is all - the attributes could be random garbage. For another example, without a copy constructor, the compiler will generate one that simply makes a bit wise copy of the attributes. If these attributes contain pointers, then you have two pointers to the same object, not necessarily a good thing, especially if one of them get "deleted".


What is use of constructor in java?

Constructor is used to do something (written in constructor) immediately after object creation.


Is it mandatory to use the construtors in a class in c plus plus?

No. If you do not provide a default constructor, the compiler will provide a default constructor that simply allocates memory for the class, but it will not initialize the members of the class. If you do not provide a copy constructor, then the compiler will provide a copy constructor that allocates memory for the class, and then copies the member's data from class to class. This is bad if the class contains pointers, because only the pointer will be copied - the objects to which the pointers point will not be copied - and you could wind up deleting an object and then using it after deletion, with potentially devastating consequences. So, yes, it is mandatory, from a good practices point of view, and just plain mandatory when the class has pointers, to always provide a default constructor and a copy constructor, along with the appropriate destructor.


What are the 6 ways to use this keyword?

"Java This keyword" is a reference to the current object, it is very helpful when you need to refer an instance of a particular Object from its available methods or using it's constructor, also "this" keyword helps us to avoid naming conflicts.The following are different ways to use java this keyword1) Using with instance variable2) Using with Constructor3) Pass / Return current instanceUsing with instance variableUsing this keyword inside a method or constructor it will use instance variable instead of local variable, in the absence of this keyword it will use local variableUsing with instance variableUsing this keyword inside a method or constructor it will use instance variable instead of local variable, in the absence of this keyword it will use local variableUsing with ConstructorUsing this keyword inside constructor like followingthis("Sony", 20); it will call the constructor having same parameter


Why you use constructor overloading?

When we are initializing our object with different internal state then we can use the constructor overloading.


Which situation constructor is used?

Constructor is necessary when you are about to use instance of a class.


What are the advantages of constructor and destructor?

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 are the advantages of pass by reference as compared to pass by value?

Call by reference, particularly when applied to objects, because call by value automatically invokes an object's copy constructor, which is seldom desirable when passing objects into functions.


What are the possibe problems if you use call by value instead of call by reference?

When you pass by value you essentially pass a temporary copy of the value. If the value's parameter is declared const, then copying the value could be costly, especially if the value is a large and complex structure or object. If the value's parameter is non-const, then it has to be assumed the function intends to alter the value in some way. If you pass by value, only the copy will be affected, not the original value. When a parameter is declared constant, passing by reference is generally the way to go. When it is non-const, pass by reference if you fully expect any changes to be reflected in the original value, otherwise pass by value.