Clarification on when constructor / Assignment Operator is used

Aug 28, 2016 at 10:17am
I would like to know exactly which function is invoked when you declare an object in this fashion:

Object newObjectName = existingObject;

I've always thought that the above statement used Copy constructor. Some student in my class claimed that the above statement is a 2-step process - Default Constructor for creating newObjectName and then assignment operator to copy the value of existingObject. Is that true?

I created a test code below. When I delete the default assignment operator (Change default to delete), I do not get an error on Line 35, which tells me that Line 35 does not utilize the assignment operator. But if I delete the default copy constructor, I do get an error on Line 35. This test tells me that the copy constructor is being used for Line 35, but I'd like to know what you think.

Thank you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
//#include "std_lib_facilities.h"

#include <iostream>

class Foo
{
public:
    // Default Constructor / One Parameter Constructor
    Foo( int val = 0 ): _value{ val } {}

    // Default Copy Constructor
    Foo( const Foo &rhs ) = default;

    // Default assignment operator
    Foo & operator= ( const Foo &rhs ) = default;

    // Accessor
    int get_value() const
    { return _value; }

private:
    int _value;
};

std::ostream & operator<< ( std::ostream &out , const Foo &x )
{
    out << x.get_value();
    return out;
}

int main()
{
    Foo foo1 { 5 };     // This should invoke the one parameter constructor

    Foo foo2 = foo1;    // Does this invoke copy constructor or Default Constructor->Assignment Operator???

    Foo foo3 {};        // This should invoke the default constructor

    foo3 = foo1;        // This should invoke the assignment operator

    Foo foo4 { foo1 };   // This should invoke the default copy constructor

    // Check that all instances of foo have the same value
    std::cout << foo1 << " " << foo2 << " " << foo3 << " " << foo4;

    return 0;
}
Last edited on Aug 28, 2016 at 10:25am
Aug 28, 2016 at 10:36am
The copy constructor

The copy constructor is called whenever an object is initialized from another object of the same type (unless overload resolution selects the move constructor as a better match), which includes

direct initialization T a(b);, where b is of type T;

copy initialization, including by-value function parameter passing, by-value returns, exception throwing and handling, and T a = b;, where b is of type T or derived from T.
http://en.cppreference.com/w/cpp/language/copy_constructor
Aug 28, 2016 at 1:16pm
Cool. Thank you!
Topic archived. No new replies allowed.