1.11M Members

Copy Constructor Question

 
0
 

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!

 
0
 

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 ;
}
 
0
 

Ah okay makes sense - thank you for the quick response!

Question Answered as of 1 Year Ago by Ancient Dragon
 
0
 

Hi,

There are two situation when copy constructor is called.
(1) if you return object from function (LunchTime function satisfy this criteria)
(2)if you pass the object as a value.(equal function satisfy this criteria)

bcoz of above two reason here copy constructor is called.

Regards,
Mohan

You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: