Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Assignment Operators in C++
Next article icon

Copy Constructor vs Assignment Operator in C++

Last Updated :13 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

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 initialized object is assigned a new value from another existing object. 
It creates a separate memory block for the new object.It does not automatically create a separate memory block or new memory space. However, if the class involves dynamic memory management, the assignment operator must first release the existing memory on the left-hand side and then allocate new memory as needed to copy the data from the right-hand side.
It is an overloaded constructor.It is a bitwise operator. 
C++ compiler implicitly provides a copy constructor, if no copy constructor is defined in the class.A bitwise copy gets created, if the Assignment operator is not overloaded. 

Syntax:

className(const className &obj) {

// body 

}

Syntax: 

className obj1, obj2;

obj2 = obj1;

Consider the following C++ program. 

CPP
// CPP Program to demonstrate the use of copy constructor// and assignment operator#include<iostream>#include<stdio.h>usingnamespacestd;classTest{public:Test(){}Test(constTest&t){cout<<"Copy constructor called "<<endl;}Test&operator=(constTest&t){cout<<"Assignment operator called "<<endl;return*this;}};// Driver codeintmain(){Testt1,t2;t2=t1;Testt3=t1;getchar();return0;}

Output
Assignment operator called Copy constructor called

Explanation:Here,t2 = t1;  calls theassignment operator, same ast2.operator=(t1); and  Test t3 = t1;  calls thecopy constructor, same asTest t3(t1);

Must Read:When is a Copy Constructor Called in C++?


Improve
Article Tags :
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp