Open In App

When is a Copy Constructor Called in C++?

Last Updated : 17 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
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 an object is constructed using initialization lists with braces 
5) When the compiler generates a temporary object. 


Below are the examples of above scenarios

1. Initialization with another object of the same type:

When an object is created by directly initializing it with another object of the same type, the copy constructor is called. For 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;
    }
};

// function that returns the object
storeVal foo()
{
    storeVal obj;
    return obj;
}

// function that takes argument of object type
void foo2(storeVal& obj) { return; }

// Driver code
int main()
{
    storeVal obj1;

    cout << "Case 1: ";
    foo();
    cout << endl;

    cout << "Case 2: ";
    foo2(obj1);
    cout << endl;

    cout << "Case 3: ";
    storeVal obj2 = obj1;

    return 0;
}

Output
Case 1: 
Case 2: 
Case 3: 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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads