views:

402

answers:

4

On page 6 of Scott Meyers's Effective C++, the term 'copy constructor' is defined. I've been using Schiltdt's book as my reference and I can find no mention of copy constructors. I get the idea but is this a standard part of c++? Will such constructors get called when a pass a class by value?

+7  A: 

Yes, copy constructors are certainly an essential part of standard C++. Read more about them (and other constructors) here (C++ FAQ).

If you have a C++ book that doesn't teach about copy constructors, throw it away. It's a bad book.

Eli Bendersky
+1  A: 

See Copy constructor on Wikipedia.

The basic idea is copy constructors instantiate new instances by copying existing ones:

class Foo {
  public:
    Foo();                // default constructor
    Foo(const Foo& foo);  // copy constructor

  // ...
};

Given an instance foo, invoke the copy constructor with

Foo bar(foo);

or

Foo bar = foo;

The Standard Template Library's containers require objects to be copyable and assignable, so if you want to use std::vector<YourClass>, be sure to have define an appropriate copy constructor and operator= if the compiler-generated defaults don't make sense.

Greg Bacon
+2  A: 

A copy constructor has the following form:

class example 
{
    example(const example&) 
    {
        // this is the copy constructor
    }
}

The following example shows where it is called.

void foo(example x);

int main(void)
{
    example x1; //normal ctor
    example x2 = x1; // copy ctor
    example x3(x2); // copy ctor

    foo(x1); // calls the copy ctor to copy the argument for foo

}
DerKuchen
Only if `foo` has the prototype `void foo(example x);`. For instance, `void foo(const example` won't call any constructors. Or `void foo(int x);` which may call a cast operator `operator int()` if not a compiler error.
KennyTM
I've edited the post to include the prototype for foo(), to make it clear.
DerKuchen
A: 

The C++ FAQ link posted by Eli is nice and gbacon's post is correct.

To explicitly answer the second part of your question: yes, when you pass an object instance by value the copy constructor will be used to create the local instance of the object in the scope of the function call. Every object has a "default copy constructor" (gbacon alludes to this as the "compiler generated default") which simply copies each object member - this may not be what you want if your object instances contain pointers or references, for example.

Regarding good books for (re)learning C++ - I first learned it almost two decades ago and it has changed a good deal since then - I recommend Bruce Eckel's "Thinking in C++" versions 1 and 2, freely available here (in both PDF and HTML form):

http://www.ibiblio.org/pub/docs/books/eckel/

Peter