• Graphics and multimedia
  • Language Features
  • Unix/Linux programming
  • Source Code
  • Standard Library
  • Tips and Tricks
  • Tools and Libraries
  • Windows API
  • Copy constructors, assignment operators,

Copy constructors, assignment operators, and exception safe assignment

*

Tech Differences

Know the Technical Differences

Difference Between Copy Constructor and Assignment Operator in C++

Copy-constructor-assignment-operator

Let us study the difference between the copy constructor and assignment operator.

Content: Copy Constructor Vs Assignment Operator

Comparison chart.

  • Key Differences

Definition of Copy Constructor

A “copy constructor” is a form of an overloaded constructor . A copy constructor is only called or invoked for initialization purpose. A copy constructor initializes the newly created object by another existing object.

When a copy constructor is used to initialize the newly created target object, then both the target object and the source object shares a different memory location. Changes done to the source object do not reflect in the target object. The general form of the copy constructor is

If the programmer does not create a copy constructor in a C++ program, then the compiler implicitly provides a copy constructor. An implicit copy constructor provided by the compiler does the member-wise copy of the source object. But, sometimes the member-wise copy is not sufficient, as the object may contain a pointer variable.

Copying a pointer variable means, we copy the address stored in the pointer variable, but we do not want to copy address stored in the pointer variable, instead, we want to copy what pointer points to. Hence, there is a need of explicit ‘copy constructor’ in the program to solve this kind of problems.

A copy constructor is invoked in three conditions as follow:

  • Copy constructor invokes when a new object is initialized with an existing one.
  • The object passed to a function as a non-reference parameter.
  • The object is returned from the function.

Let us understand copy constructor with an example.

In the code above, I had explicitly declared a constructor “copy( copy &c )”. This copy constructor is being called when object B is initialized using object A. Second time it is called when object C is being initialized using object A.

When object D is initialized using object A the copy constructor is not called because when D is being initialized it is already in the existence, not the newly created one. Hence, here the assignment operator is invoked.

Definition of Assignment Operator

The assignment operator is an assigning operator of C++.  The “=” operator is used to invoke the assignment operator. It copies the data in one object identically to another object. The assignment operator copies one object to another member-wise. If you do not overload the assignment operator, it performs the bitwise copy. Therefore, you need to overload the assignment operator.

In above code when object A is assigned to object B the assignment operator is being invoked as both the objects are already in existence. Similarly, same is the case when object C is initialized with object A.

When the bitwise assignment is performed both the object shares the same memory location and changes in one object reflect in another object.

Key Differences Between Copy Constructor and Assignment Operator

  • A copy constructor is an overloaded constructor whereas an assignment operator is a bitwise operator.
  • Using copy constructor you can initialize a new object with an already existing object. On the other hand, an assignment operator copies one object to the other object, both of which are already in existence.
  • A copy constructor is initialized whenever a new object is initialized with an already existing object, when an object is passed to a function as a non-reference parameter, or when an object is returned from a function. On the other hand, an assignment operator is invoked only when an object is being assigned to another object.
  • When an object is being initialized using copy constructor, the initializing object and the initialized object shares the different memory location. On the other hand, when an object is being initialized using an assignment operator then the initialized and initializing objects share the same memory location.
  • If you do not explicitly define a copy constructor then the compiler provides one. On the other hand, if you do not overload an assignment operator then a bitwise copy operation is performed.

The Copy constructor is best for copying one object to another when the object contains raw pointers.

Related Differences:

  • Difference Between & and &&
  • Difference Between Recursion and Iteration
  • Difference Between new and malloc( )
  • Difference Between Inheritance and Polymorphism
  • Difference Between Constructor and Destructor

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

cppreference.com

Copy constructors.

A copy constructor is a constructor which can be called with an argument of the same class type and copies the content of the argument without mutating the argument.

[ edit ] Syntax

[ edit ] explanation.

The copy constructor is called whenever an object is initialized (by direct-initialization or copy-initialization ) from another object of the same type (unless overload resolution selects a better match or the call is elided ), which includes

  • initialization: T a = b ; or T a ( b ) ; , where b is of type T ;
  • function argument passing: f ( a ) ; , where a is of type T and f is void f ( T t ) ;
  • function return: return a ; inside a function such as T f ( ) , where a is of type T , which has no move constructor .

[ edit ] Implicitly-declared copy constructor

If no user-defined copy constructors are provided for a class type, the compiler will always declare a copy constructor as a non- explicit inline public member of its class. This implicitly-declared copy constructor has the form T :: T ( const T & ) if all of the following are true:

  • each direct and virtual base B of T has a copy constructor whose parameters are of type const B & or const volatile B & ;
  • each non-static data member M of T of class type or array of class type has a copy constructor whose parameters are of type const M & or const volatile M & .

Otherwise, the implicitly-declared copy constructor is T :: T ( T & ) .

Due to these rules, the implicitly-declared copy constructor cannot bind to a volatile lvalue argument.

A class can have multiple copy constructors, e.g. both T :: T ( const T & ) and T :: T ( T & ) .

The implicitly-declared (or defaulted on its first declaration) copy constructor has an exception specification as described in dynamic exception specification (until C++17) noexcept specification (since C++17) .

[ edit ] Implicitly-defined copy constructor

If the implicitly-declared copy constructor is not deleted, it is defined (that is, a function body is generated and compiled) by the compiler if odr-used or needed for constant evaluation (since C++11) . For union types, the implicitly-defined copy constructor copies the object representation (as by std::memmove ). For non-union class types, the constructor performs full member-wise copy of the object's direct bases and non-static data members, in their initialization order, using direct initialization.

[ edit ] Deleted copy constructor

The implicitly-declared or explicitly-defaulted (since C++11) copy constructor for class T is undefined (until C++11) defined as deleted (since C++11) if any of the following conditions is satisfied:

  • T has a potentially constructed subobject of class type M (or possibly multi-dimensional array thereof) such that
  • M has a destructor that is deleted or (since C++11) inaccessible from the copy constructor, or
  • the overload resolution as applied to find M 's copy constructor
  • does not result in a usable candidate, or
  • in the case of the subobject being a variant member , selects a non-trivial function.

[ edit ] Trivial copy constructor

The copy constructor for class T is trivial if all of the following are true:

  • it is not user-provided (that is, it is implicitly-defined or defaulted);
  • T has no virtual member functions;
  • T has no virtual base classes;
  • the copy constructor selected for every direct base of T is trivial;
  • the copy constructor selected for every non-static class type (or array of class type) member of T is trivial;

A trivial copy constructor for a non-union class effectively copies every scalar subobject (including, recursively, subobject of subobjects and so forth) of the argument and performs no other action. However, padding bytes need not be copied, and even the object representations of the copied subobjects need not be the same as long as their values are identical.

TriviallyCopyable objects can be copied by copying their object representations manually, e.g. with std::memmove . All data types compatible with the C language (POD types) are trivially copyable.

[ edit ] Eligible copy constructor

Triviality of eligible copy constructors determines whether the class is an implicit-lifetime type , and whether the class is a trivially copyable type .

[ edit ] Notes

In many situations, copy constructors are optimized out even if they would produce observable side-effects, see copy elision .

[ edit ] Example

[ edit ] defect reports.

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

[ edit ] See also

  • converting constructor
  • copy assignment
  • copy elision
  • default constructor
  • aggregate initialization
  • constant initialization
  • copy initialization
  • default initialization
  • direct initialization
  • initializer list
  • list initialization
  • reference initialization
  • value initialization
  • zero initialization
  • move assignment
  • move constructor
  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 2 February 2024, at 09:23.
  • This page has been accessed 1,248,882 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

Trending Articles on Technical and Non Technical topics

  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Copy constructor vs assignment operator in C++

The Copy constructor and the assignment operators are used to initializing one object to another object. The main difference between them is that the copy constructor creates a separate memory block for the new object. But the assignment operator does not make new memory space. It uses the reference variable to point to the previous memory block.

Copy Constructor (Syntax)

Assignment operator (syntax).

Let us see the detailed differences between Copy constructor and Assignment Operator.

Ankith Reddy

Related Articles

  • Difference Between Copy Constructor and Assignment Operator in C++
  • What's the difference between assignment operator and copy constructor in C++?
  • Copy Constructor in C++
  • Virtual Copy Constructor in C++
  • What is an assignment operator in C#?
  • How to use an assignment operator in C#?
  • What is a copy constructor in C#?
  • When is copy constructor called in C++?
  • When should we write our own assignment operator in C++?
  • What is Multiplication Assignment Operator (*=) in JavaScript?
  • What is Addition Assignment Operator (+=) in JavaScript?
  • When should we write our own assignment operator in C++ programming?
  • Explain the concept of logical and assignment operator in C language
  • Ternary operator ?: vs if…else in C/C++
  • What is Bitwise OR Assignment Operator (|=) in JavaScript?

Kickstart Your Career

Get certified by completing the course

To Continue Learning Please Login

Pediaa.Com

Home » Technology » IT » Programming » What is the Difference Between Copy Constructor and Assignment Operator

What is the Difference Between Copy Constructor and Assignment Operator

The main difference between copy constructor and assignment operator is that copy constructor is a type of constructor that helps to create a copy of an already existing object without affecting the values of the original object while assignment operator is an operator that helps to assign a new value to a variable in the program.

A constructor is a special method that helps to initialize an object when creating it. It has the same name as the class name and has no return type. A programmer can write a constructor to give initial values to the instance variables in the class. If there is no constructor in the program, the default constructor will be called. Copy constructor is a type of constructor that helps to create a copy of an existing object. On the other hand, assignment operator helps to assign a new value to a variable.

Key Areas Covered

1. What is Copy Constructor      – Definition, Functionality 2. What is Assignment Operator      – Definition, Functionality 3. What is the Difference Between Copy Constructor and Assignment Operator      – Comparison of Key Differences

Constructor, Copy Constructor, Assignment Operator, Variable

Difference Between Copy Constructor and Assignment Operator - Comparison Summary

What is Copy Constructor

In programming, sometimes it is necessary to create a separate copy of an object without affecting the original object. Copy constructor is useful in these situations. It allows creating a replication of an existing object of the same class. Refer the below example.

What is the Difference Between Copy Constructor and Assignment Operator

Figure 1: Program with copy constructor

The class Triangle has two instance variables called base and height. In line 8, there is a parameterized constructor. It takes two arguments. These values are assigned to the instance variables base and height. In line 13, there is a copy constructor. It takes an argument of type Triangle. New object’s base value is assigned to the instance variable base. Similarly, the new object’s height value is assigned to the instance variable height. Furthermore, there is a method called calArea to calculate and return area.

In the main method, t1 and t2 are Triangle objects. The object t1 is passed when creating the t2 object. The copy constructor is called to create t2 object. Therefore, the base and the height of the t2 object is the same as the base and height of t1 object. Finally, both objects have the same area.    

What is Assignment Operator

An assignment operator is useful to assign a new value to a variable. The assignment operator is “=”.  When there is a statement as c = a + b; the summation of ‘a’ and ‘b’ is assigned to the variable ‘c’.

Main Difference - Copy Constructor vs Assignment Operator

Figure 2: Program with assignment operator

The class Number has an instance variable called num. There is a no parameter constructor in line 7. However, there is a parameterized constructor in line 9. It takes an argument and assigns it to the instance variable using the assignment operator. In line 12, there is a method called display to display the number. In the main method, num1 and num2 are two objects of type Number. Printing num1 and num2 gives the references to those objects. The num3 is of type Number. In line 24, num1 is assigned to num3 using the assignment operator. Therefore, num3 is referring to num1 object. So, printing num3 gives the num1 reference.  

The assignment operator and its variations are as follows.

Difference Between Copy Constructor and Assignment Operator

Copy constructor is a special constructor for creating a new object as a copy of an existing object. In contrast, assignment operator is an operator that is used to assign a new value to a variable. These definitions explain the basic difference between copy constructor and assignment operator.

Functionality with Objects

Functionality with objects is also a major difference between copy constructor and assignment operator. Copy constructor initializes the new object with an already existing object while assignment operator assigns the value of one object to another object which is already in existence.

Copy constructor helps to create a copy of an existing object while assignment operator helps to assign a new value to a variable. This is another difference between copy constructor and assignment operator.

The difference between copy constructor and assignment operator is that copy constructor is a type of constructor that helps to create a copy of an already existing object without affecting the values of the original object while assignment operator is an operator that helps to assign a new value to a variable in the program.

1. Thakur, Dinesh. “Copy Constructor in Java Example.” Computer Notes, Available here .

' src=

About the Author: Lithmee

Lithmee holds a Bachelor of Science degree in Computer Systems Engineering and is reading for her Master’s degree in Computer Science. She is passionate about sharing her knowldge in the areas of programming, data science, and computer systems.

​You May Also Like These

Leave a reply cancel reply.

Learn C++

21.12 — Overloading the assignment operator

The copy assignment operator (operator=) is used to copy values from one object to another already existing object .

Related content

As of C++11, C++ also supports “Move assignment”. We discuss move assignment in lesson 22.3 -- Move constructors and move assignment .

Copy assignment vs Copy constructor

The purpose of the copy constructor and the copy assignment operator are almost equivalent -- both copy one object to another. However, the copy constructor initializes new objects, whereas the assignment operator replaces the contents of existing objects.

The difference between the copy constructor and the copy assignment operator causes a lot of confusion for new programmers, but it’s really not all that difficult. Summarizing:

  • If a new object has to be created before the copying can occur, the copy constructor is used (note: this includes passing or returning objects by value).
  • If a new object does not have to be created before the copying can occur, the assignment operator is used.

Overloading the assignment operator

Overloading the copy assignment operator (operator=) is fairly straightforward, with one specific caveat that we’ll get to. The copy assignment operator must be overloaded as a member function.

This prints:

This should all be pretty straightforward by now. Our overloaded operator= returns *this, so that we can chain multiple assignments together:

Issues due to self-assignment

Here’s where things start to get a little more interesting. C++ allows self-assignment:

This will call f1.operator=(f1), and under the simplistic implementation above, all of the members will be assigned to themselves. In this particular example, the self-assignment causes each member to be assigned to itself, which has no overall impact, other than wasting time. In most cases, a self-assignment doesn’t need to do anything at all!

However, in cases where an assignment operator needs to dynamically assign memory, self-assignment can actually be dangerous:

First, run the program as it is. You’ll see that the program prints “Alex” as it should.

Now run the following program:

You’ll probably get garbage output. What happened?

Consider what happens in the overloaded operator= when the implicit object AND the passed in parameter (str) are both variable alex. In this case, m_data is the same as str.m_data. The first thing that happens is that the function checks to see if the implicit object already has a string. If so, it needs to delete it, so we don’t end up with a memory leak. In this case, m_data is allocated, so the function deletes m_data. But because str is the same as *this, the string that we wanted to copy has been deleted and m_data (and str.m_data) are dangling.

Later on, we allocate new memory to m_data (and str.m_data). So when we subsequently copy the data from str.m_data into m_data, we’re copying garbage, because str.m_data was never initialized.

Detecting and handling self-assignment

Fortunately, we can detect when self-assignment occurs. Here’s an updated implementation of our overloaded operator= for the MyString class:

By checking if the address of our implicit object is the same as the address of the object being passed in as a parameter, we can have our assignment operator just return immediately without doing any other work.

Because this is just a pointer comparison, it should be fast, and does not require operator== to be overloaded.

When not to handle self-assignment

Typically the self-assignment check is skipped for copy constructors. Because the object being copy constructed is newly created, the only case where the newly created object can be equal to the object being copied is when you try to initialize a newly defined object with itself:

In such cases, your compiler should warn you that c is an uninitialized variable.

Second, the self-assignment check may be omitted in classes that can naturally handle self-assignment. Consider this Fraction class assignment operator that has a self-assignment guard:

If the self-assignment guard did not exist, this function would still operate correctly during a self-assignment (because all of the operations done by the function can handle self-assignment properly).

Because self-assignment is a rare event, some prominent C++ gurus recommend omitting the self-assignment guard even in classes that would benefit from it. We do not recommend this, as we believe it’s a better practice to code defensively and then selectively optimize later.

The copy and swap idiom

A better way to handle self-assignment issues is via what’s called the copy and swap idiom. There’s a great writeup of how this idiom works on Stack Overflow .

The implicit copy assignment operator

Unlike other operators, the compiler will provide an implicit public copy assignment operator for your class if you do not provide a user-defined one. This assignment operator does memberwise assignment (which is essentially the same as the memberwise initialization that default copy constructors do).

Just like other constructors and operators, you can prevent assignments from being made by making your copy assignment operator private or using the delete keyword:

Note that if your class has const members, the compiler will instead define the implicit operator= as deleted. This is because const members can’t be assigned, so the compiler will assume your class should not be assignable.

If you want a class with const members to be assignable (for all members that aren’t const), you will need to explicitly overload operator= and manually assign each non-const member.

guest

  • C++ Classes and Objects
  • C++ Polymorphism

C++ Inheritance

  • C++ Abstraction
  • C++ Encapsulation
  • C++ OOPs Interview Questions
  • C++ OOPs MCQ

C++ Interview Questions

C++ function overloading.

  • C++ Programs
  • C++ Preprocessor

C++ Templates

  • C++ Programming Language

C++ Overview

  • Introduction to C++ Programming Language
  • Features of C++
  • History of C++
  • Interesting Facts about C++
  • Setting up C++ Development Environment
  • Difference between C and C++
  • Writing First C++ Program - Hello World Example
  • C++ Basic Syntax
  • C++ Comments
  • Tokens in C
  • C++ Keywords
  • Difference between Keyword and Identifier

C++ Variables and Constants

  • C++ Variables
  • Constants in C
  • Scope of Variables in C++
  • Storage Classes in C++ with Examples
  • Static Keyword in C++

C++ Data Types and Literals

  • C++ Data Types
  • Literals in C
  • Derived Data Types in C++
  • User Defined Data Types in C++
  • Data Type Ranges and their macros in C++
  • C++ Type Modifiers
  • Type Conversion in C++
  • Casting Operators in C++

C++ Operators

  • Operators in C++
  • C++ Arithmetic Operators
  • Unary operators in C
  • Bitwise Operators in C
  • Assignment Operators in C
  • C++ sizeof Operator
  • Scope resolution operator in C++

C++ Input/Output

  • Basic Input / Output in C++
  • cout in C++
  • cerr - Standard Error Stream Object in C++
  • Manipulators in C++ with Examples

C++ Control Statements

  • Decision Making in C (if , if..else, Nested if, if-else-if )
  • C++ if Statement
  • C++ if else Statement
  • C++ if else if Ladder
  • Switch Statement in C++
  • Jump statements in C++
  • for Loop in C++
  • Range-based for loop in C++
  • C++ While Loop
  • C++ Do/While Loop

C++ Functions

  • Functions in C++
  • return statement in C++ with Examples
  • Parameter Passing Techniques in C
  • Difference Between Call by Value and Call by Reference in C
  • Default Arguments in C++
  • Inline Functions in C++
  • Lambda expression in C++

C++ Pointers and References

  • Pointers and References in C++
  • C++ Pointers
  • Dangling, Void , Null and Wild Pointers in C
  • Applications of Pointers in C
  • Understanding nullptr in C++
  • References in C++
  • Can References Refer to Invalid Location in C++?
  • Pointers vs References in C++
  • Passing By Pointer vs Passing By Reference in C++
  • When do we pass arguments by pointer?
  • Variable Length Arrays (VLAs) in C
  • Pointer to an Array | Array Pointer
  • How to print size of array parameter in C++?
  • Pass Array to Functions in C
  • What is Array Decay in C++? How can it be prevented?

C++ Strings

  • Strings in C++
  • std::string class in C++
  • Array of Strings in C++ - 5 Different Ways to Create
  • String Concatenation in C++
  • Tokenizing a string in C++
  • Substring in C++

C++ Structures and Unions

  • Structures, Unions and Enumerations in C++
  • Structures in C++
  • C++ - Pointer to Structure
  • Self Referential Structures
  • Difference Between C Structures and C++ Structures
  • Enumeration in C++
  • typedef in C++
  • Array of Structures vs Array within a Structure in C

C++ Dynamic Memory Management

  • Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
  • new and delete Operators in C++ For Dynamic Memory
  • new vs malloc() and free() vs delete in C++
  • What is Memory Leak? How can we avoid?
  • Difference between Static and Dynamic Memory Allocation in C

C++ Object-Oriented Programming

  • Object Oriented Programming in C++
  • Access Modifiers in C++
  • Friend Class and Function in C++
  • Constructors in C++
  • Default Constructors in C++

Copy Constructor in C++

  • Destructors in C++
  • Private Destructor in C++
  • When is a Copy Constructor Called in C++?
  • Shallow Copy and Deep Copy in C++
  • When Should We Write Our Own Copy Constructor in C++?
  • Does C++ compiler create default constructor when we write our own?
  • C++ Static Data Members
  • Static Member Function in C++
  • 'this' pointer in C++
  • Scope Resolution Operator vs this pointer in C++
  • Local Classes in C++
  • Nested Classes in C++
  • Enum Classes in C++ and Their Advantage over Enum DataType
  • Difference Between Structure and Class in C++
  • Why C++ is partially Object Oriented Language?

C++ Encapsulation and Abstraction

  • Encapsulation in C++
  • Abstraction in C++
  • Difference between Abstraction and Encapsulation in C++
  • Function Overriding in C++
  • Virtual Functions and Runtime Polymorphism in C++
  • Difference between Inheritance and Polymorphism
  • Function Overloading in C++
  • Constructor Overloading in C++
  • Functions that cannot be overloaded in C++
  • Function overloading and const keyword
  • Function Overloading and Return Type in C++
  • Function Overloading and float in C++
  • C++ Function Overloading and Default Arguments
  • Can main() be overloaded in C++?
  • Function Overloading vs Function Overriding in C++
  • Advantages and Disadvantages of Function Overloading in C++

C++ Operator Overloading

  • Operator Overloading in C++
  • Types of Operator Overloading in C++
  • Functors in C++
  • What are the Operators that Can be and Cannot be Overloaded in C++?
  • Inheritance in C++
  • C++ Inheritance Access
  • Multiple Inheritance in C++
  • C++ Hierarchical Inheritance
  • C++ Multilevel Inheritance
  • Constructor in Multiple Inheritance in C++
  • Inheritance and Friendship in C++
  • Does overloading work with Inheritance?

C++ Virtual Functions

  • Virtual Function in C++
  • Virtual Functions in Derived Classes in C++
  • Default Arguments and Virtual Function in C++
  • Can Virtual Functions be Inlined in C++?
  • Virtual Destructor
  • Advanced C++ | Virtual Constructor
  • Advanced C++ | Virtual Copy Constructor
  • Pure Virtual Functions and Abstract Classes in C++
  • Pure Virtual Destructor in C++
  • Can Static Functions Be Virtual in C++?
  • RTTI (Run-Time Type Information) in C++
  • Can Virtual Functions be Private in C++?

C++ Exception Handling

  • Exception Handling in C++
  • Exception Handling using classes in C++
  • Stack Unwinding in C++
  • User-defined Custom Exception with class in C++

C++ Files and Streams

  • File Handling through C++ Classes
  • I/O Redirection in C++
  • Templates in C++ with Examples
  • Template Specialization in C++
  • Using Keyword in C++ STL

C++ Standard Template Library (STL)

  • The C++ Standard Template Library (STL)
  • Containers in C++ STL (Standard Template Library)
  • Introduction to Iterators in C++
  • Algorithm Library | C++ Magicians STL Algorithm

C++ Preprocessors

  • C Preprocessors
  • C Preprocessor Directives
  • #include in C
  • Difference between Preprocessor Directives and Function Templates in C++

C++ Namespace

  • Namespace in C++ | Set 1 (Introduction)
  • namespace in C++ | Set 2 (Extending namespace and Unnamed namespace)
  • Namespace in C++ | Set 3 (Accessing, creating header, nesting and aliasing)
  • C++ Inline Namespaces and Usage of the "using" Directive Inside Namespaces

Advanced C++

  • Multithreading in C++
  • Smart Pointers in C++
  • auto_ptr vs unique_ptr vs shared_ptr vs weak_ptr in C++
  • Type of 'this' Pointer in C++
  • "delete this" in C++
  • Passing a Function as a Parameter in C++
  • Signal Handling in C++
  • Generics in C++
  • Difference between C++ and Objective C
  • Write a C program that won't compile in C++
  • Write a program that produces different results in C and C++
  • How does 'void*' differ in C and C++?
  • Type Difference of Character Literals in C and C++
  • Cin-Cout vs Scanf-Printf

C++ vs Java

  • Similarities and Difference between Java and C++
  • Comparison of Inheritance in C++ and Java
  • How Does Default Virtual Behavior Differ in C++ and Java?
  • Comparison of Exception Handling in C++ and Java
  • Foreach in C++ and Java
  • Templates in C++ vs Generics in Java
  • Floating Point Operations & Associativity in C, C++ and Java

Competitive Programming in C++

  • Competitive Programming - A Complete Guide
  • C++ tricks for competitive programming (for C++ 11)
  • Writing C/C++ code efficiently in Competitive programming
  • Why C++ is best for Competitive Programming?
  • Test Case Generation | Set 1 (Random Numbers, Arrays and Matrices)
  • Fast I/O for Competitive Programming
  • Setting up Sublime Text for C++ Competitive Programming Environment
  • How to setup Competitive Programming in Visual Studio Code for C++
  • Which C++ libraries are useful for competitive programming?
  • Common mistakes to be avoided in Competitive Programming in C++ | Beginners
  • C++ Interview Questions and Answers (2024)
  • Top C++ STL Interview Questions and Answers
  • 30 OOPs Interview Questions and Answers (2024)
  • Top C++ Exception Handling Interview Questions and Answers
  • C++ Programming Examples

Pre-requisite: Constructor in C++ 

A copy constructor is a member function 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 .  

Copy constructor is used to initialize the members of a newly created object by copying the members of an already existing object.

Copy constructor takes a reference to an object of the same class as an argument.

The process of initializing members of an object through a copy constructor is known as copy initialization.

It is also called member-wise initialization because the copy constructor initializes one object with the existing object, both belonging to the same class on a member by member copy basis.

The copy constructor can be defined explicitly by the programmer. If the programmer does not define the copy constructor, the compiler does it for us.  

Syntax of Copy Constructor with Example

Syntax of Copy Constructor

Characteristics of Copy Constructor

1. The copy constructor is used to initialize the members of a newly created object by copying the members of an already existing object.

2. Copy constructor takes a reference to an object of the same class as an argument. If you pass the object by value in the copy constructor, it would result in a recursive call to the copy constructor itself. This happens because passing by value involves making a copy, and making a copy involves calling the copy constructor, leading to an infinite loop. Using a reference avoids this recursion. So we use reference of Objects to avoid infinite calls.

3. The process of initializing members of an object through a copy constructor is known as copy initialization.

4 . It is also called member-wise initialization because the copy constructor initializes one object with the existing object, both belonging to the same class on a member-by-member copy basis.

5. The copy constructor can be defined explicitly by the programmer. If the programmer does not define the copy constructor, the compiler does it for us.

Types of Copy Constructors

1. default copy constructor.

An implicitly defined copy constructor will copy the bases and members of an object in the same order that a constructor would initialize the bases and members of the object.

2. User Defined Copy Constructor 

A user-defined copy constructor is generally needed when an object owns pointers or non-shareable references, such as to a file, in which case a destructor and an assignment operator should also be written

When is the copy constructor called? 

In C++, a Copy Constructor may be called in the following cases: 

  • When an object of the class is returned by value. 
  • When an object of the class 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.

It is, however, not guaranteed that a copy constructor will be called in all these cases, because the C++ Standard allows the compiler to optimize the copy away in certain cases, one example is the return value optimization (sometimes referred to as RVO).

Copy Elision

In copy elision , the compiler prevents the making of extra copies which results in saving space and better the program complexity(both time and space); Hence making the code more optimized.  

Now it is on the compiler to decide what it wants to print, it could either print the above output or it could print case 1 or case 2 below, and this is what Return Value Optimization is. In simple words, RVO is a technique that gives the compiler some additional power to terminate the temporary object created which results in changing the observable behavior/characteristics of the final program.

When is a user-defined copy constructor needed? 

If we don’t define our own copy constructor, the C++ compiler creates a default copy constructor for each class which does a member-wise copy between objects. The compiler-created copy constructor works fine in general. We need to define our own copy constructor only if an object has pointers or any runtime allocation of the resource like a file handle , a network connection, etc.  

The default constructor does only shallow copy.  

shallow copy in C++

Deep copy is possible only with a user-defined copy constructor. In a user-defined copy constructor, we make sure that pointers (or references) of copied objects point to new memory locations.  

Deep Copy in C++

Copy constructor vs Assignment Operator 

The main difference between Copy Constructor and Assignment Operator is that the Copy constructor makes a new memory storage every time it is called while the assignment operator does not make new memory storage.

Which of the following two statements calls the copy constructor and which one calls the assignment operator? 

A copy constructor is called when a new object is created from an existing object, as a copy of the existing object. The assignment operator is called when an already initialized object is assigned a new value from another existing object. In the above example (1) calls the copy constructor and (2) calls the assignment operator. See this for more details.

Example – Class Where a Copy Constructor is Required 

Following is a complete C++ program to demonstrate the use of the Copy constructor. In the following String class, we must write a copy constructor. 

What would be the problem if we remove the copy constructor from the above code? 

If we remove the copy constructor from the above program, we don’t get the expected output. The changes made to str2 reflect in str1 as well which is never expected.   

Can we make the copy constructor private?  

Yes, a copy constructor can be made private. When we make a copy constructor private in a class, objects of that class become non-copyable. This is particularly useful when our class has pointers or dynamically allocated resources. In such situations, we can either write our own copy constructor like the above String example or make a private copy constructor so that users get compiler errors rather than surprises at runtime.

Why argument to a copy constructor must be passed as a reference?  

A copy constructor is called when an object is passed by value. Copy constructor itself is a function. So if we pass an argument by value in a copy constructor, a call to the copy constructor would be made to call the copy constructor which becomes a non-terminating chain of calls. Therefore compiler doesn’t allow parameters to be passed by value.

Why argument to a copy constructor should be const?

One reason for passing const reference is, that 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 than ‘ Why argument to a copy constructor should be const?’

Please Login to comment...

Similar reads.

  • cpp-constructor

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Copy constructors and copy assignment operators (C++)

  • 8 contributors

Starting in C++11, two kinds of assignment are supported in the language: copy assignment and move assignment . In this article "assignment" means copy assignment unless explicitly stated otherwise. For information about move assignment, see Move Constructors and Move Assignment Operators (C++) .

Both the assignment operation and the initialization operation cause objects to be copied.

Assignment : When one object's value is assigned to another object, the first object is copied to the second object. So, this code copies the value of b into a :

Initialization : Initialization occurs when you declare a new object, when you pass function arguments by value, or when you return by value from a function.

You can define the semantics of "copy" for objects of class type. For example, consider this code:

The preceding code could mean "copy the contents of FILE1.DAT to FILE2.DAT" or it could mean "ignore FILE2.DAT and make b a second handle to FILE1.DAT." You must attach appropriate copying semantics to each class, as follows:

Use an assignment operator operator= that returns a reference to the class type and takes one parameter that's passed by const reference—for example ClassName& operator=(const ClassName& x); .

Use the copy constructor.

If you don't declare a copy constructor, the compiler generates a member-wise copy constructor for you. Similarly, if you don't declare a copy assignment operator, the compiler generates a member-wise copy assignment operator for you. Declaring a copy constructor doesn't suppress the compiler-generated copy assignment operator, and vice-versa. If you implement either one, we recommend that you implement the other one, too. When you implement both, the meaning of the code is clear.

The copy constructor takes an argument of type ClassName& , where ClassName is the name of the class. For example:

Make the type of the copy constructor's argument const ClassName& whenever possible. This prevents the copy constructor from accidentally changing the copied object. It also lets you copy from const objects.

Compiler generated copy constructors

Compiler-generated copy constructors, like user-defined copy constructors, have a single argument of type "reference to class-name ." An exception is when all base classes and member classes have copy constructors declared as taking a single argument of type const class-name & . In such a case, the compiler-generated copy constructor's argument is also const .

When the argument type to the copy constructor isn't const , initialization by copying a const object generates an error. The reverse isn't true: If the argument is const , you can initialize by copying an object that's not const .

Compiler-generated assignment operators follow the same pattern for const . They take a single argument of type ClassName& unless the assignment operators in all base and member classes take arguments of type const ClassName& . In this case, the generated assignment operator for the class takes a const argument.

When virtual base classes are initialized by copy constructors, whether compiler-generated or user-defined, they're initialized only once: at the point when they are constructed.

The implications are similar to the copy constructor. When the argument type isn't const , assignment from a const object generates an error. The reverse isn't true: If a const value is assigned to a value that's not const , the assignment succeeds.

For more information about overloaded assignment operators, see Assignment .

Was this page helpful?

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

Copy assignment operator

A copy assignment operator of class T is a non-template non-static member function with the name operator = that takes exactly one parameter of type T , T & , const T & , volatile T & , or const volatile T & . A type with a public copy assignment operator is CopyAssignable .

[ edit ] Syntax

[ edit ] explanation.

  • Typical declaration of a copy assignment operator when copy-and-swap idiom can be used
  • Typical declaration of a copy assignment operator when copy-and-swap idiom cannot be used
  • Forcing a copy assignment operator to be generated by the compiler
  • Avoiding implicit copy assignment

The copy assignment operator is called whenever selected by overload resolution , e.g. when an object appears on the left side of an assignment expression.

[ edit ] Implicitly-declared copy assignment operator

If no user-defined copy assignment operators are provided for a class type ( struct , class , or union ), the compiler will always declare one as an inline public member of the class. This implicitly-declared copy assignment operator has the form T & T :: operator = ( const T & ) if all of the following is true:

  • each direct base B of T has a copy assignment operator whose parameters are B or const B& or const volatile B &
  • each non-static data member M of T of class type or array of class type has a copy assignment operator whose parameters are M or const M& or const volatile M &

Otherwise the implicitly-declared copy assignment operator is declared as T & T :: operator = ( T & ) . (Note that due to these rules, the implicitly-declared copy assignment operator cannot bind to a volatile lvalue argument)

A class can have multiple copy assignment operators, e.g. both T & T :: operator = ( const T & ) and T & T :: operator = ( T ) . If some user-defined copy assignment operators are present, the user may still force the generation of the implicitly declared copy assignment operator with the keyword default .

Because the copy assignment operator is always declared for any class, the base class assignment operator is always hidden. If a using-declaration is used to bring in the assignment operator from the base class, and its argument type could be the same as the argument type of the implicit assignment operator of the derived class, the using-declaration is also hidden by the implicit declaration.

[ edit ] Deleted implicitly-declared copy assignment operator

The implicitly-declared or defaulted copy assignment operator for class T is defined as deleted in any of the following is true:

  • T has a non-static data member that is const
  • T has a non-static data member of a reference type.
  • T has a non-static data member that cannot be copy-assigned (has deleted, inaccessible, or ambiguous copy assignment operator)
  • T has direct or virtual base class that cannot be copy-assigned (has deleted, inaccessible, or ambiguous move assignment operator)
  • T has a user-declared move constructor
  • T has a user-declared move assignment operator

[ edit ] Trivial copy assignment operator

The implicitly-declared copy assignment operator for class T is trivial if all of the following is true:

  • T has no virtual member functions
  • T has no virtual base classes
  • The copy assignment operator selected for every direct base of T is trivial
  • The copy assignment operator selected for every non-static class type (or array of class type) memeber of T is trivial

A trivial copy assignment operator makes a copy of the object representation as if by std:: memmove . All data types compatible with the C language (POD types) are trivially copy-assignable.

[ edit ] Implicitly-defined copy assignment operator

If the implicitly-declared copy assignment operator is not deleted or trivial, it is defined (that is, a function body is generated and compiled) by the compiler. For union types, the implicitly-defined copy assignment copies the object representation (as by std:: memmove ). For non-union class types ( class and struct ), the operator performs member-wise copy assignment of the object's bases and non-static members, in their initialization order, using, using built-in assignment for the scalars and copy assignment operator for class types.

The generation of the implicitly-defined copy assignment operator is deprecated (since C++11) if T has a user-declared destructor or user-declared copy constructor.

[ edit ] Notes

If both copy and move assignment operators are provided, overload resolution selects the move assignment if the argument is an rvalue (either prvalue such as a nameless temporary or xvalue such as the result of std:: move ), and selects the copy assignment if the argument is lvalue (named object or a function/operator returning lvalue reference). If only the copy assignment is provided, all argument categories select it (as long as it takes its argument by value or as reference to const, since rvalues can bind to const references), which makes copy assignment the fallback for move assignment, when move is unavailable.

[ edit ] Copy and swap

Copy assignment operator can be expressed in terms of copy constructor, destructor, and the swap() member function, if one is provided:

T & T :: operator = ( T arg ) { // copy/move constructor is called to construct arg     swap ( arg ) ;     // resources exchanged between *this and arg     return * this ; }   // destructor is called to release the resources formerly held by *this

For non-throwing swap(), this form provides strong exception guarantee . For rvalue arguments, this form automatically invokes the move constructor, and is sometimes referred to as "unifying assignment operator" (as in, both copy and move).

[ edit ] Example

IMAGES

  1. Difference between copy constructor and assignment operator in c++

    copy assignment operator vs copy constructor

  2. Difference Between Copy Constructor And Assignment Operator In C++ #183

    copy assignment operator vs copy constructor

  3. Difference between Copy Constructor and Assignment Operator,Copy

    copy assignment operator vs copy constructor

  4. What is the Difference Between Copy Constructor and Assignment Operator

    copy assignment operator vs copy constructor

  5. Difference Between Copy Constructor and Assignment Operator in C++

    copy assignment operator vs copy constructor

  6. Copy Constructor in C++ vs. Assignment Operator in C++: What’s the

    copy assignment operator vs copy constructor

VIDEO

  1. PROGRAM TO COPY CONSTRUCTOR IN C++

  2. NOTES COPY CONSTRUCTOR IN C++

  3. COMSC210 Module7 6

  4. COMSC210 Module4 3

  5. copy constructor code by c++ #copyconstructor #shortsfeed

  6. C++ class copy constructor [3]

COMMENTS

  1. What's the difference between assignment operator and copy constructor?

    A copy constructor is used to initialize a previously uninitialized object from some other object's data. A(const A& rhs) : data_(rhs.data_) {} For example: A aa; A a = aa; //copy constructor An assignment operator is used to replace the data of a previously initialized object with some other object's data.

  2. Copy Constructor vs Assignment Operator in C++

    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 object. This operator is called when an already initialized object is assigned a new value from another existing object. It creates a separate memory block for ...

  3. The copy constructor and assignment operator

    The copy constructor is for creating a new object. It copies an existing object to a newly constructed object.The copy constructor is used to initialize a new instance from an old instance. It is not necessarily called when passing variables by value into functions or as return values out of functions. The assignment operator is to deal with an ...

  4. Copy constructors and copy assignment operators (C++)

    Use an assignment operator operator= that returns a reference to the class type and takes one parameter that's passed by const reference—for example ClassName& operator=(const ClassName& x);. Use the copy constructor. If you don't declare a copy constructor, the compiler generates a member-wise copy constructor for you.

  5. Copy assignment operator

    Triviality of eligible copy assignment operators determines whether the class is a trivially copyable type. [] NoteIf both copy and move assignment operators are provided, overload resolution selects the move assignment if the argument is an rvalue (either a prvalue such as a nameless temporary or an xvalue such as the result of std::move), and selects the copy assignment if the argument is an ...

  6. Difference Between Copy Constructor and Assignment Operator in C++

    The difference between a copy constructor and an assignment operator is that a copy constructor helps to create a copy of an already existing object without altering the original value of the created object, whereas an assignment operator helps to assign a new value to a data member or an object in the program. Kiran Kumar Panigrahi.

  7. Copy constructors, assignment operators,

    The first line runs the copy constructor of T, which can throw; the remaining lines are assignment operators which can also throw. HOWEVER, if you have a type T for which the default std::swap() may result in either T's copy constructor or assignment operator throwing, you are

  8. 14.14

    The rule of three is a well known C++ principle that states that if a class requires a user-defined copy constructor, destructor, or copy assignment operator, then it probably requires all three. In C++11, this was expanded to the rule of five , which adds the move constructor and move assignment operator to the list.

  9. Difference Between Copy Constructor and Assignment Operator in C++

    Copy constructor and assignment operator, are the two ways to initialize one object using another object. The fundamental difference between the copy constructor and assignment operator is that the copy constructor allocates separate memory to both the objects, i.e. the newly created target object and the source object. The assignment operator allocates the same memory location to the newly ...

  10. Copy constructors

    A copy constructor is a constructor which can be called with an argument of the same class type and copies the content of the argument without mutating the argument. ... generation of the implicitly-defined copy constructor is deprecated if T has a user-defined destructor or user-defined copy assignment operator. (since C++11)

  11. Copy constructor vs assignment operator in C++

    The Copy constructor and the assignment operators are used to initializing one object to another object. The main difference between them is that the copy constructor creates a separate memory block for the new object. But the assignment operator does not make new memory space. It uses the reference variable to point to the previous memory block.

  12. PDF Copy Constructors and Assignment Operators

    the assignment operator is called only when assigning an existing object a new value. Otherwise, you're using the copy constructor. What C++ Does For You Unless you specify otherwise, C++ will automatically provide objects a basic copy constructor and assignment operator that simply invoke the copy constructors and assignment operators of all ...

  13. What is the Difference Between Copy Constructor and Assignment Operator

    Conclusion. The difference between copy constructor and assignment operator is that copy constructor is a type of constructor that helps to create a copy of an already existing object without affecting the values of the original object while assignment operator is an operator that helps to assign a new value to a variable in the program.

  14. 21.12

    Copy assignment vs Copy constructor. The purpose of the copy constructor and the copy assignment operator are almost equivalent -- both copy one object to another. ... The difference between the copy constructor and the copy assignment operator causes a lot of confusion for new programmers, but it's really not all that difficult. Summarizing:

  15. C++ at Work: Copy Constructors, Assignment Operators, and More

    Both classes have a copy constructor and assignment operator, with the copy constructor for CMainClass calling operator= as in the first snippet. The code is sprinkled with printf statements to show which methods are called when. To exercise the constructors, cctest first creates an instance of CMainClass using the default ctor, then creates ...

  16. Copy Constructor in C++

    A copy constructor is called when a new object is created from an existing object, as a copy of the existing object. The assignment operator is called when an already initialized object is assigned a new value from another existing object. In the above example (1) calls the copy constructor and (2) calls the assignment operator.

  17. Copy constructors and copy assignment operators (C++)

    Starting in C++11, two kinds of assignment are supported in the language: copy assignment and move assignment. In this article "assignment" means copy assignment unless explicitly stated otherwise. For information about move assignment, see

  18. Copy assignment operator

    The copy assignment operator selected for every non-static class type (or array of class type) memeber of T is trivial. A trivial copy assignment operator makes a copy of the object representation as if by std::memmove. All data types compatible with the C language (POD types) are trivially copy-assignable.

  19. C++ : Implementing copy constructor and copy assignment operator

    Instead, what you want to do is implement the assignment operator in terms of the copy constructor. Then, you should implement the copy-constructor in terms of a non-throwing swap function. Read about the Copy & Swap idiom for details. Also, the default constructor of Foobar doesn't default-initialize the members.

  20. c++

    The move assignment operator takes an r-value reference only e.g. CLASSA a1, a2, a3; a1 = a2 + a3; In the copy assignment operator, other can be constructor using a copy constructor or a move constructor (if other is initialized with an rvalue, it could be move-constructed --if move-constructor defined--). If it is copy-constructed, we will be ...

  21. Does the assignment operator call copy constructor?

    Here also bit by bit copy is done (a.p and b.p pointing to same location), it does not invoke copy constructor because constructor is called when b in defined (default constructor).so you have to overload = operator. test &operator =(const test &src) {. *this->p=*src.p; //copy value not address. return *this;

  22. How to call operator= or destructor of superclass?

    Using this approach, C::operator=() would be implemented to call A::operator=() and to allocate/copy/release c. Furthermore, the destructors of B and C should generally not release A s members. When B and C are destructed, A s constructor is called implicitly (so your approach will result in A::name being destroyed twice, which results in ...