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.
#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) ;
}