the program is self-explanatory. My question is on line
Base b = func(a);
I thought there should be three copy constructor called in this line, but there are actually only two.
If I do
Base b = a;
one copy constructor will be called. Why not here? as func itself will generate two copy constructors.
Thanks
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Base{
public:
Base(string n){
name = n;
cout << "Base() " << name << endl;
}
Base(const Base&){cout << "Base(const Base&)" << name << endl;}
~Base(){cout << "~Base() " << name << endl;}
Base & operator = (const Base & other)
{
if (this != &other) // protect against invalid self-assignment
{
// 1: allocate new memory and copy the elements
//int * new_array = new int[other.count];
//std::copy(other.array, other.array + other.count, new_array);
//// 2: deallocate old memory
//delete [] array;
//// 3: assign the new memory to the object
//array = new_array;
//count = other.count;
}
cout << " in assignment " << name << endl;
// by convention, always return *this
return *this;
}
The compiler is smart and is eliding a copy constructor. Because it knows that func(a)'s result is really going
into b, func(a)'s return is copying the value directly to b instead of to a temporary location that would then
later get copied to b.