I have the following piece of code:
#include<iostream> using namespace std; class A{ int size; double *arr; public: A(int len):size(len) { cout<<"ctor called"<<endl; arr=new double[size]; } A(const A &rhs) { cout<<"calling copy ctor"<<endl; size=rhs.size; arr=new double[size]; } ~A() { cout<<"calling dtor"<<endl; delete[] arr; arr=NULL; size=0; } }; A createVector() { cout<<"Creating object"<<endl; A a(10); cout<<"returning after creating object a"<<endl; return a; } void foo(A v) { cout<<"Class A object rcvd"<<endl; //return v; } int main() { A a=createVector(); cout<<"a has been rcvd"<<endl; foo(a); return 0; } And I have the following output:
Creating object ctor called returning after creating object a a has been rcvd calling copy ctor Class A object rcvd calling dtor calling dtor I am having trouble with createVector() function. When I return a object by value,its copy constructor should be called but I am not seeing any output between the lines
returning after creating object a a has been rcvd Why copy constructor has not been called??
(when I pass the rcvd object as value to foo(),Copy Constructor gets called)