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!

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

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.