The Wayback Machine - https://web.archive.org/web/20231217182303/https://www.geeksforgeeks.org/when-is-a-copy-constructor-called-in-cpp/
Open In App
Related Articles

When is a Copy Constructor Called in C++?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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) When an object of the class is passed (to a function) by value as an argument. 
3) When an object is constructed based on another object of the same class. 
4) When the compiler generates a temporary object. 

Example:

C++




// CPP Program to demonstrate the use of copy constructor
#include <iostream>
#include <stdio.h>
using namespace std;
  
class storeVal {
public:
    // Constructor
    storeVal() {}
    // Copy Constructor
    storeVal(const storeVal& s)
    {
        cout << "Copy constructor has been called " << endl;
    }
};
  
// Driver code
int main()
{
    storeVal obj1;
    storeVal obj2 = obj1;
    getchar();
    return 0;
}


Output

Copy constructor has been called 

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 being the Return Value Optimization (sometimes referred to as RVO). 

Note: C++ compiler implicitly provides a copy constructor, if no copy constructor is defined in the class.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 29 Nov, 2021
Like Article
Save Article
Previous
Next
Similar Reads