Consider the belo code snippet:
class Base
{
public:
Base()
{
cout<<"Constructor"<<endl;
}
Base(const Base& rhs)
{
cout<<"Copy constructor"<<endl;
}
Base* Clone()
{
return new Base(*this); <--------------- 2
}
void* operator new(size_t size)
{
void* p=malloc(size);
cout<<"Inside new"<<endl;
return p;
}
};
int main()
{
Base b1; <------------ 1
Base* ptr=b1.Clone();
return 0;
}
I am getting the output as:
Constructor
Inside new
Copy constructor
I kept hearing that first operator new allocates a chunk of void type & then new operator calls constructor to convert that chunk into the exact type as that on the LHS.
So, why the constructor is not getting called for statement 2?
I also want to know the exact series of actions undertaken by the C++ compiler for the statement 2.
It is. Where do you think
"Copy constructor"comes from?Output:
Constructorcalls
which in turn calls your
operator newand then your copy constructor.