The Wayback Machine - https://web.archive.org/web/20241007223417/https://www.geeksforgeeks.org/copy-constructor-argument-const/
Open In App

Why copy constructor argument should be const in C++?

Last Updated : 01 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

When we create our own copy constructor, we pass an object by reference and we generally pass it as a const reference. 
One reason for passing const reference is, we should use const in C++ wherever possible so that objects are not accidentally modified. This is one good reason for passing reference as const, but there is more to it. For example, predict the output of following C++ program. Assume that copy elision is not done by compiler.

C++
#include<iostream>
using namespace std;

class Test
{
/* Class data members */
public:
Test(Test &t) { /* Copy data members from t*/}
Test()     { /* Initialize data members */ }
};

Test fun()
{
    cout << "fun() Called\n";
    Test t;
    return t;
}

int main()
{
    Test t1;
    Test t2 = fun();
    return 0;
}

Output: 

 Compiler Error in line "Test t2 = fun();" 


The program looks fine at first look, but it has compiler error. If we add const in copy constructor, the program works fine, i.e., we change copy constructor to following. 
 

C++
Test(const Test &t) { cout << "Copy Constructor Called\n"; }

Or if we change the line “Test t2 = fun();” to following two lines, then also the program works fine.
 

C++
  Test t2; 
  t2 = fun();

In the above codes, what’s actually happening?

It gets executed but the copy constructor is not called, instead, it calls the default constructor where the assignment operator is overloaded. Even if we have an explicitly overloaded assignment operator, it is not going to call it. 

The function fun() returns by value. So the compiler creates a temporary object which is copied to t2 using the copy constructor in the original program (The temporary object is passed as an argument to the copy constructor). The reason for compiler error is that compiler-created temporary objects cannot be bound to non-const references and the original program tries to do that. It doesn’t make sense to modify compiler-created temporary objects as they can die at any moment. (generally at the end of the full expression where it is created)

In simpler terms,

In C++, temporary objects are objects that are created during the evaluation of an expression, typically for immediate use and  to be copied to any named variable.

The error “compiler created temporary objects cannot be bound to non-const references” is related to binding temporary objects to non-const references. This means that a temporary object cannot be directly assigned to a non-const reference variable.
To resolve this, you have two options:

1. Use a const reference in the function parameter to increase the lifetime of the temporary object.
2. Use a named variable to store the value and then pass it to the function.

Using a const reference allows you to read the value but not modify it within the function, which is a common approach when working with temporary objects. Alternatively, using a named variable ensures that the object’s lifetime extends to the function call and beyond, avoiding the issue with temporaries.


This article is compiled by Abhay Rathi.
 



Similar Reads

Difference between const char *p, char * const p and const char * const p
Prerequisite: Pointers There is a lot of confusion when char, const, *, p are all used in different permutations and meanings change according to which is placed where. Following article focus on differentiation and usage of all of these. The qualifier const can be applied to the declaration of any variable to specify that its value will not be cha
3 min read
When Should We Write Our Own Copy Constructor in C++?
A copy constructor is a member function that initializes an object using another object of the same class. (See this article for reference). When should we write our own copy constructor?C++ compiler provides a default copy constructor (and assignment operator) with class. When we don't provide an implementation of the copy constructor (and assignm
2 min read
Why can't a const variable be used to define an Array's initial size in C?
What is an array? An array is a collection of items of the same data type stored at contiguous memory locations. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array). The base value is index
3 min read
Advanced C++ | Virtual Copy Constructor
In the virtual constructor idiom we have seen the way to construct an object whose type is not determined until runtime. Is it possible to create an object without knowing it's exact class type? The virtual copy constructor address this question.Sometimes we may need to construct an object from another existing object. Precisely the copy constructo
5 min read
When is a Copy Constructor Called in C++?
A copy constructor is a member function that initializes an object using another object of the same class. The Copy constructor is called mainly when a new object is created from an existing object, as a copy of the existing object. In C++, a Copy Constructor may be called for the following cases: 1) When an object of the class is returned by value
2 min read
Copy Constructor in C++
A copy constructor is a type of constructor that initializes an object using another object of the same class. In simple terms, a constructor which creates an object by initializing it with an object of the same class, which has been created previously is known as a copy constructor.   The process of initializing members of an object through a copy
7 min read
Copy Constructor vs Assignment Operator in C++
Copy constructor and Assignment operator are similar as they are both used to initialize one object using another object. But, there are some basic differences between them: Copy constructor Assignment operator It is called when a new object is created from an existing object, as a copy of the existing objectThis operator is called when an already
2 min read
Different methods to copy in C++ STL | std::copy(), copy_n(), copy_if(), copy_backward()
Various varieties of copy() exist in C++ STL that allows to perform the copy operations in different manners, all of them having their own use. These all are defined in header <algorithm>. This article introduces everyone to these functions for usage in day-to-day programming. 1. copy(strt_iter1, end_iter1, strt_iter2) : The generic copy func
5 min read
Shallow Copy and Deep Copy in C++
In general, creating a copy of an object means to create an exact replica of the object having the same literal value, data type, and resources. There are two ways that are used by C++ compiler to create a copy of objects. Copy ConstructorAssignment Operator// Copy Constructor Geeks Obj1(Obj); or Geeks Obj1 = Obj; // Default assignment operator Gee
6 min read
C++ | const keyword | Question 1
Predict the output of following program #include <iostream> using namespace std; int main() { const char* p = "12345"; const char **q = &p; *q = "abcde"; const char *s = ++p; p = "XYZWVU"; cout << *++s; return 0; } (A) Compiler Error (B) c (C) b (D) Garbage Value Answer: (B) Explanation: Output is ‘c’ c
1 min read
C++ | const keyword | Question 2
In C++, const qualifier can be applied to 1) Member functions of a class 2) Function arguments 3) To a class data member which is declared as static 4) Reference variables (A) Only 1, 2 and 3 (B) Only 1, 2 and 4 (C) All (D) Only 1, 3 and 4 Answer: (C) Explanation: When a function is declared as const, it cannot modify data members of its class. Whe
1 min read
C++ | const keyword | Question 3
Predict the output of following program. #include <iostream> using namespace std; class Point { int x, y; public: Point(int i = 0, int j =0) { x = i; y = j; } int getX() const { return x; } int getY() {return y;} }; int main() { const Point t; cout << t.getX() << " "; cout << t.getY(); return 0; } (A) Garbage Value
1 min read
C++ | const keyword | Question 5
#include <stdio.h> int main() { const int x; x = 10; printf("%d", x); return 0; } (A) Compiler Error (B) 10 (C) 0 (D) Runtime Error Answer: (A) Explanation: One cannot change the value of 'const' variable except at the time of initialization. Compiler does check this.Quiz of this Question
1 min read
C++ | const keyword | Question 5
Output of C++ program? #include <iostream> int const s=9; int main() { std::cout << s; return 0; } Contributed by Pravasi Meet (A) 9 (B) Compiler Error Answer: (A) Explanation: The above program compiles & runs fine. Const keyword can be put after the variable type or before variable type. But most programmers prefer to put const ke
1 min read
“static const” vs “#define” vs “enum”
In this article, we will be analyzing "static const", "#define" and "enum". These three are often confusing and choosing which one to use can sometimes be a difficult task. static const static const : "static const" is basically a combination of static(a storage specifier) and const(a type qualifier). Static : determines the lifetime and visibility
4 min read
Const Qualifier in C
The qualifier const can be applied to the declaration of any variable to specify that its value will not be changed (which depends upon where const variables are stored, we may change the value of the const variable by using a pointer). The result is implementation-defined if an attempt is made to change a const. Using the const qualifier in C is a
7 min read
Function overloading and const keyword
Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading. In Function Overloading “Function” name should be the same and the arguments should be different. Function overloading
5 min read
Const member functions in C++
Constant member functions are those functions that are denied permission to change the values of the data members of their class. To make a member function constant, the keyword const is appended to the function prototype and also to the function definition header. Like member functions and member function arguments, the objects of a class can also
6 min read
Difference between #define and const in C?
#define is a preprocessor directive. Data defined by the #define macro definition are preprocessed, so that your entire code can use it. This can free up space and increase compilation times.const variables are considered variables, and not macro definitions. Long story short: CONSTs are handled by the compiler, where as #DEFINEs are handled by the
2 min read
How to modify a const variable in C?
Whenever we use const qualifier with variable name, it becomes a read-only variable and get stored in .rodata segment. Any attempt to modify this read-only variable will then result in a compilation error: "assignment of read-only variable". In the below program, a read-only variable declared using the const qualifier is tried to modify: [GFGTABS]
2 min read
Const keyword in C++
In this article, the various functions of the const keyword which is found in C++ are discussed. Whenever const keyword is attached with any method(), variable, pointer variable, and with the object of a class it prevents that specific object/method()/variable to modify its data items value. Constant Variables:There are certain set of rules for the
10 min read
Variable Length Argument in C
Variable length argument is a feature that allows a function to receive any number of arguments. There are situations where we want a function to handle variable number of arguments according to requirement. 1) Sum of given numbers. 2) Minimum of given numbers. and many more. Variable number of arguments are represented by three dotes (...) Below i
3 min read
Argument Coercion in C/C++
Argument coercion is a feature of function prototypes by which the compiler implicitly converts the datatype of the arguments passed during the function call to match the datatype in the definition of the function. It follows Argument promotion rules. Therefore a lower datatype maybe converted into a higher datatype but vice-versa is not true. This
1 min read
Difference between Argument and Parameter in C/C++ with Examples
Argument An argument is referred to the values that are passed within a function when the function is called. These values are generally the source of the function that require the arguments during the process of execution. These values are assigned to the variables in the definition of the function that is called. The type of the values passed in
4 min read
Class Template Argument Deduction in C++17
In this article, we will learn about Class Template Argument Deduction(CTAD) in C++17 and with examples. CTAD is a feature in C++17 that allows the template arguments to be deduced from constructor arguments. In simple words, we can say that instead of explicitly specifying the template arguments the compiler can automatically deduce them based on
4 min read
Why we should avoid using std::endl
It is a common practice to use std::endl to print newlines while using cout. For small programs with very little I/O operations this practice is acceptable, but if the bulk of I/O operations increase, then the efficiency of the program is compromised. std::endl not only adds newlines to the stream, it also flushes the buffer each time it is used.Th
3 min read
Why Should We Not Inherit std::vector in C++?
In C++, you may sometime want to inherit vector in your class to make the use of already present functionality. But inheriting from std::vector is generally discouraged due to various technical and design issues. In this article, we will explore why inheriting from std::vector is problematic. We will also look at some practical alternatives for ext
3 min read
Why Should We Not Derive from C++ std::string Class?
In C++, we might sometimes think of deriving from the std::string class to use its existing functionality while adding our own enhancements. However, deriving from std::string is generally discouraged due to several technical and design concerns. In this article, we will learn why inheriting from std::string is problematic and discuss some practica
4 min read
What is conversion constructor in C++?
Pre-requisite: Type Conversion in C++ and Use of explicit keyword in C++ A conversion constructor is a single-parameter constructor that is declared without the function specifier explicitly. The compiler uses conversion constructors to convert objects from the type of the first parameter to the type of the conversion constructor's class. Example:
3 min read
Passing a vector to constructor in C++
When class member is a vector object (not a reference).We can simply assign in constructor. C/C++ Code // Passing vector object to a constructor. #include &lt;iostream&gt; #include &lt;vector&gt; using namespace std; class MyClass { vector&lt;int&gt; vec; public: MyClass(vector&lt;int&gt; v) { vec = v; } void print()
2 min read
Article Tags :
Practice Tags :