We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,585 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

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!

3
Contributors
3
Replies
2 Months
Discussion Span
3 Months Ago
Last Updated
8
Views
Question
Answered
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
Team Colleague
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

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

can-mohan
Newbie Poster
19 posts since Feb 2013
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0718 seconds using 2.76MB