I have read copy constructor is called when "Copy an object to return it from a function."
So I understand the copy constructor is called whenever we return a object is my understanding correct?
If yes, then whenever we return an object the constructor will be called. So, If we were in a mid of program copy constructor will be called. Then values will be assigned to the data member of the class. So the existing value will be replaced?
If no, what is the meaning of the sentence?
SRC: Tutorial point
#include <iostream>
using namespace std;
class demo
{
public:
int rate;
demo(int init_rate);
demo( const demo &obj_passed);
demo display();
};
demo::demo(int init_rate)
{
cout << "\nNormal Construtor" << endl;
rate=init_rate;
}
demo::demo(const demo &obj_passed) // Copy Constructor
{
cout << "\nCopy constructor" << endl;
rate=obj_passed.rate;
}
demo demo::display()
{
demo temp(10);
temp.rate=45;
return temp; //copy constructor is not called here
}
int main( )
{
demo obj1=obj1.display();
return 0;
}
and output is
Normal Constructor