In object-oriented programming, a constructor in a class is a special block of statements called when an object lifetime#Creating objects, either when it is declared or dynamically constructed on the heap-based memory allocation through the keyword ?new?.... in the C++
C++
C++ is a general-purpose programming language. It is regarded as a middle-level language, as it comprises a combination of both high-level programming language and low-level programming language language features.... programming language
Programming language
A programming language is a machine-readable artificial language designed to express computations that can be performed by a machine, particularly a computer.... used to create a new object
Object (computer science)
In its simplest embodiment, an object is an allocated region of storage. Since programming languages use variable#Computer_programmings to access objects, the terms object and variable are often used interchangeably.... as a copy
Object copy
One of the most common procedures that occurs in computer programs is the copying of data. An object is a composite data type in object-oriented programming languages.... of an existing object. This constructor takes a single
argument: a reference
Reference (computer science)
In computer science, a reference is an object containing information about how to locate and access the particular data item, as opposed to containing the data itself.... to the object to be copied.
A compiler is a computer program that transforms source code written in a programming language into another computer language . The most common reason for wanting to transform source code is to create an executable program.... automatically creates a copy constructor for each class
Class (computer science)
In object-oriented programming, a class is a programming language construct that is used as a blueprint to create Object s. This blueprint includes Attribute s and Method s that the created objects all share.... (known as an implicit copy constructor) but for special cases the programmer
Programmer
A programmer is someone who writes computer software. The term computer programmer can refer to a specialist in one area of computer programming or to a generalist who writes code for many kinds of software.... creates the copy constructor, known as an explicit copy constructor.
In object-oriented programming, a constructor in a class is a special block of statements called when an object lifetime#Creating objects, either when it is declared or dynamically constructed on the heap-based memory allocation through the keyword ?new?.... in the C++
C++
C++ is a general-purpose programming language. It is regarded as a middle-level language, as it comprises a combination of both high-level programming language and low-level programming language language features.... programming language
Programming language
A programming language is a machine-readable artificial language designed to express computations that can be performed by a machine, particularly a computer.... used to create a new object
Object (computer science)
In its simplest embodiment, an object is an allocated region of storage. Since programming languages use variable#Computer_programmings to access objects, the terms object and variable are often used interchangeably.... as a copy
Object copy
One of the most common procedures that occurs in computer programs is the copying of data. An object is a composite data type in object-oriented programming languages.... of an existing object. This constructor takes a single
argument: a reference
Reference (computer science)
In computer science, a reference is an object containing information about how to locate and access the particular data item, as opposed to containing the data itself.... to the object to be copied.
A compiler is a computer program that transforms source code written in a programming language into another computer language . The most common reason for wanting to transform source code is to create an executable program.... automatically creates a copy constructor for each class
Class (computer science)
In object-oriented programming, a class is a programming language construct that is used as a blueprint to create Object s. This blueprint includes Attribute s and Method s that the created objects all share.... (known as an implicit copy constructor) but for special cases the programmer
Programmer
A programmer is someone who writes computer software. The term computer programmer can refer to a specialist in one area of computer programming or to a generalist who writes code for many kinds of software.... creates the copy constructor, known as an explicit copy constructor. In such cases, the compiler doesn't create
one.
A copy constructor is generally needed when an object owns pointers
Data pointer
In computer science, a pointer is a programming language data type whose value refers directly to another value stored elsewhere in the computer memory using its Memory address.... or non-shareable references
Reference (computer science)
In computer science, a reference is an object containing information about how to locate and access the particular data item, as opposed to containing the data itself.... , such as to a file
Computer file
A computer file is a block of arbitrary information, or resource for storing information, which is available to a computer program and is usually based on some kind of durable computer storage.... , in which case a destructor
Destructor (computer science)
In object-oriented programming, a destructor is a method which is automatically invoked when the object is destroyed. Its main purpose is to clean up and to free the Resource which were acquired by the object along its life cycle and unlink it from other objects or resources invalidating any references in the process.... and an assignment operator
Assignment operator in C++
The assignment operator in C++ programming language is '='. Like most other operators in C++, it can be Operator overloading.The copy assignment operator is a special case of assignment operator used to assign objects of the same class to each other.... should also be written (see Rule of three
Rule of three (C++ programming)
The rule of three is a rule of thumb in C++ that claims that if a Class Declaration one of the following it should probably explicitly define all three:... ).
Definition
Copying of objects is achieved by the use of a copy constructor and a copy assignment operator
Assignment (computer science)
In computer science the assignment statement sets or re-sets the Value stored in the storage location denoted by a variable name. In most imperative programming computer programming languages the assignment statement is one of the basic Statement s.... . A copy constructor has as its first parameter a (possibly const or volatile) reference to its own class type. It can have more arguments, but the rest must have default values associated with them. The following would be valid copy constructors for class X:
X(X const& copyFromMe);
X(X& copyFromMe);
X(X const volatile& copyFromMe);
X(X volatile& copyFromMe);
X(X const& copyFromMe, int = 10);
X(X const& copyFromMe, double = 1.0, int = 40);
The first one should be used unless there is a good reason to use one of the others. One of the differences between the first and the second is that temporaries can be copied with the first. For example:
X a = X; // valid! a temporary variable is not a const.
Another difference between them is the obvious:
X const a;
X b = a; // valid if you have X(X const& copyFromMe) but not valid if you have X(X& copyFromMe)
// because the second wants a non-const X&
The X& form of the copy constructor is used when it is necessary to modify the copied object. This is very rare but it can be seen used in the standard library's stdauto_ptr. A reference must be provided:
X a;
X b = a; // valid if any of the copy constructors is defined
// since you're passing in a reference
The following are invalid copy constructors (or regular constructors):
X(X copyFromMe);
X(X const copyFromMe);
because the call to those constructors would require a copy as well, which would result in an infinitely recursive call.
There are four cases where a copy constructor is called:
When an object is returned by value
When an object is passed (to a function) by value as an argument
When an object is constructed based on another object (of the same class)
When the compiler generates a temporary object (as in 1 and 2 above; as in explicit casting, etc...)
Operation
An object can be assigned value using one of the two techniques:
Explicit assignment in an expression
Initialization
Explicit assignment in an expression
Object A;
Object B;
A = B; // translates as Objectoperator=(const Object&), thus A.operator=(B) is called
// (invoke simple copy, not copy constructor!)
Initialization
An object can be initialized by any one of the following ways.
a. Through declaration
Object B = A; // translates as ObjectObject(const Object&) (invoke copy constructor)
b. Through function arguments
type function (Object a);
c. Through function return value
Object a = function;
The copy constructor is used only in latter case (initializations) and doesn't apply to assignments where the assignment operator is used instead.
The implicit copy constructor of a class calls base copy constructors and copies its members by means appropriate to their type. If it is a class type, the copy constructor is called. If it is a scalar type, the built-in assignment operator is used. Finally, if it is an array, each element is copied in the manner appropriate to its type.
By using an explicit copy constructor the programmer can define the behavior to be performed when an object is copied.
Examples
These examples illustrate how copy constructors work and why they are required sometimes.
Implicit copy constructor
Let us consider the following example.
include
class Person
;
int main
Output
10 15 10
23 15 10
As expected, timmy has been copied to the new object, timmy_clone. While timmy's age was changed, timmy_clone's age remained the same. This is because they are totally different objects.
The compiler has generated a copy constructor for us, and it could be written like this:
Person(Person const& copy)
: age(copy.age)
So, when do we really need an explicit copy constructor? The next section will explore that question.
Explicit copy constructor
Now, consider a very simple dynamic array class like the following:
include
class Array
;
int main
Output
25 25
Segmentation fault
Since we didn't specify a copy constructor, the compiler generated one for us. The generated constructor would look something like:
Array(Array const& copy)
: size(copy.size), data(copy.data)
The problem with this constructor is that it performs a shallow copy of the data pointer. It only copies the address of the original data member; this means they both share a pointer to the same chunk of memory, which is not what we want. When the program reaches line (1), copy's destructor gets called (because objects on the stack are destroyed automatically when their scope ends).
Array's destructor deletes the data array of the original, therefore when it deleted copy's data, because they share the same pointer, it also deleted first's data. Line (2) now accesses invalid data and writes to it! This produces the famous segmentation fault
Segmentation fault
A segmentation fault is a particular error condition that can occur during the operation of computer software. A segmentation fault occurs when a program attempts to access a memory location that it is not allowed to access, or attempts to access a memory location in a way that is not allowed .... .
If we write our own copy constructor that performs a deep copy then this problem goes away.
Array(Array const& copy)
: size(copy.size), data(new int[copy.size])
Here, we are creating a new int array and copying the contents to it. Now, copy's destructor only deletes its data and not first's data as well. Line (2) will not produce a segmentation fault anymore.
Instead of doing a deep copy right away, there are some optimization strategies that can be used. These allow you to safely share the same data between several objects, thus saving space. The copy on write strategy makes a copy of the data only when it is written to. Reference counting
Reference counting
In computer science, reference counting is a technique of storing the number of references, pointers, or handles to a resource such as an object or block of memory.... keeps the count of how many objects are referencing the data, and will delete it only when this count reaches zero (e.g boostshared_ptr).
Copy constructors and templates
Contrary to expectations, a template copy constructor is not an explicit copy constructor. Thus it is not enough to just have:
template ArrayArray(const A& copy)
: size(copy.size), data(new int[copy.size])
(Note that the type of A can be Array.) An explicit, non-template, copy constructor must also be provided for construction of Array from Array.
The assignment operator in C++ programming language is '='. Like most other operators in C++, it can be Operator overloading.The copy assignment operator is a special case of assignment operator used to assign objects of the same class to each other....
One of the most common procedures that occurs in computer programs is the copying of data. An object is a composite data type in object-oriented programming languages....