Why is copy constructor not called

Viewed 552

Here is a simple class header file and a main program. In the main program, I thought that the copy constructor is called in exactly three situations: initialization(explicit copy), pass by value for function arguments, and return by value for functions. However it seems like it is not being called for one of them, I think either (3) or (4) as numbered in the comments. For which numbers (1) - (4) does it get called? Thanks.

X.h:

#include <iostream>

class X
{
public:
    X() {std::cout << "default constructor \n";}
    X(const X& x) { std::cout << "copy constructor \n";}
};

Main:

#include "X.h"

X returnX(X b)  // (1) pass by value - call copy constructor?
{
    X c = b;  // (2) explicit copy - call copy constructor?
    return b;  // (3) return by value - call copy constructor?
}

int main()
{
    X a; // calls default constructor

    std::cout << "calling returnX \n\n";
    X d = returnX(a);  // (4) explicit copy - call copy constructor?
    std::cout << "back in main \n";
}

Output:

default constructor
calling returnX

copy constructor
copy constructor
copy constructor 
back in main
2 Answers
Related