Copy Constructor Question
Hi all!
I just have a quick question about the execution of a copy constructor. This is the code i'm testing my work with as I'm busy learning for a test.
Class file:
Clock :: Clock (int h, int m, int s)
{
hr = h;
min = m;
sec = s;
cout << " Default constructor " << endl ;
}
Clock :: Clock ( const Clock & c)
{
hr = c.hr;
min = c.min ;
sec = c.sec ;
cout << " Copy constructor " << endl ;
}
Clock Clock :: LunchTime () {
hr = 12;
min = 0;
sec = 0;
return * this ;
}
bool Clock :: equal ( const Clock c)
{
return hr == c.hr && min == c.min && sec == c.sec ;
}
Then in the main :
int main () {
Clock c1 (12 ,0 ,0);
Clock c2;
c2. LunchTime ();
if (c1. equal (c2))
cout << " Times are equal " << endl ;
}
My question is why is it that the c2.LunchTime() triggers the copy constructor? And with the next line if (c1. equal (c2)) it also calls the copy constructor?
Any help will be appreciated!
Related Article: Copy Constructor Question
is a C++ discussion thread by MRehanQadri that has 1 reply and was last updated 2 months ago.
Phillamon
Junior Poster in Training
95 posts since Oct 2010
Reputation Points: 36
Solved Threads: 5
Skill Endorsements: 1
why is it that the c2.LunchTime() triggers the copy constructor?
Because the function is returning an object and the only way to return it is by making copy of it. If you changed it like this then the copy constructor would not get called because the function would return a reference to itself.
Clock& Clock :: LunchTime () {
hr = 12;
min = 0;
sec = 0;
return this ;
}
Ancient Dragon
Achieved Level 70
32,109 posts since Aug 2005
Reputation Points: 5,836
Solved Threads: 2,575
Skill Endorsements: 68
Ah okay makes sense - thank you for the quick response!
Phillamon
Junior Poster in Training
95 posts since Oct 2010
Reputation Points: 36
Solved Threads: 5
Skill Endorsements: 1
Question Answered as of 5 Months Ago by
Ancient Dragon