When a copy constructor is called

Apr 27, 2013 at 1:07am
The following are the cases when copy constructor is called.
1)When instantiating one object and initializing it with values from another object.
2)When passing an object by value.
3)When an object is returned from a function by value.

I don't understand #2 How can and object be passed by value? when I think of passing object I think of passing by address or reference. explain

I don't understand #3 how can a function returned object by value I think of again passing by address or reference.

I am learning C++ this may be more of a beginners question but I don't like the way the Russian guy explain things.
Apr 27, 2013 at 1:24am
Apr 27, 2013 at 4:21am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

struct A
{
    A() {}
    A( const A& ) { std::cout << "A::copy_constructor is called to make a copy\n" ; }
};

void foo( A object ) { std::cout << "foo has recieved a copy of an object\n"  ; }
A bar() { std::cout << "bar - about to return an object by value\n" ; static A a ; return a ; }

int main()
{
    std::cout << "about to call bar\n" ;
    A object = bar() ;
    std::cout << "bar has returned\n" ;

    std::cout << "\n\nabout to call foo\n" ;
    foo(object) ;
}


http://ideone.com/fjNuRk
Apr 27, 2013 at 9:33am
1
2
3
4
5
6
7
8
struct A
{
        // other stuff
        A( A&& ) { std::cout << "A::move_constructor is called to make a copy\n" ; }
};


A object = bar() ;
Apr 27, 2013 at 9:48am
> A( A&& ) { std::cout << "A::move_constructor is called to make a copy\n" ; }
> A object = bar() ;

In practice, the move constructor will never be used in this particular program.

bar() can't use the move constructor to make a copy.
And RVO enables copy-elision of the anonymous return value.

http://ideone.com/iWp77h
Topic archived. No new replies allowed.