[ACCEPTED]-What is a copy constructor in C++?-constructor

Accepted answer
Score: 16

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

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

Score: 13

A copy constructor has the following form:

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

The 1 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

}
Score: 4

See Copy constructor on Wikipedia.

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

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

  // ...
};

Given an instance 7 foo, invoke the copy constructor with

Foo bar(foo);

or

Foo bar = foo;

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

Score: 2

Copy constructor will be called in then 9 following scenarios:

  • When creating new objects 8 from an existing object.

    MyClass Obj1;
    MyClass Obj2 = Obj1; // Here assigning Obj1 to newly created Obj2
    

    or

    MyClass Obj1;
    MyClass Obj2(Obj1);
    
  • When passing class 7 object by value.

    void NewClass::TestFunction( MyClass inputObject_i )
    {
      // Function body
    }
    

    Above MyClass object passed 6 by value. So copy constructor of MyClass 5 will call. Pass by reference to avoid copy 4 constructor calling.

  • When returning objects 3 by value

    MyClass NewClass::Get()
    {
      return ObjMyClass;
    }
    

    Above MyClass is returned by value, So 2 copy constructor of MyClass will call. Pass 1 by reference to avoid copy constructor calling.

Score: 1

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

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

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

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

Score: 1

Copy Constructor is an essential part of 10 C++. Even-though any C++ compiler provides 9 default copy constructor if at all if we 8 don't define it explicitly in the class, We 7 write copy constructor for the class for 6 the following two reasons.

  1. If there is any dynamic memory allocation in the class.
  2. If we use pointer variables inside the class. (otherwise it will be a shallow copy in which 2 objects will point to the same memory location.)

To make a deep 5 copy, you must write a copy constructor 4 and overload the assignment operator, otherwise 3 the copy will point to the original, with 2 disastrous consequences.

The copy constructor 1 syntax would be written as below:

class Sample{

public:
   Sample (const Sample &sample);

};

int main()
{

   Sample s1;
   Sample s2 = s1;   // Will invoke Copy Constructor.
   Sample s3(s1);     //This will also invoke copy constructor.

   return 0;
}
Score: 1

A copy constructor is a constructor which 10 does deep copy. You should write your own 9 copy constructor when there is a pointer 8 type variable inside the class. Compiler 7 will insert copy constructor automatically 6 when there is no explicit copy constructor 5 written inside the code. The type of a copy 4 constructor parameter should always be reference 3 type, this to avoid infinite recursion due 2 to the pass by value type.

below program 1 explains the use of copy constructor

#include <iostream>
#pragma warning(disable : 4996)
using namespace std;
class SampleTest {
private:
    char* name;
    int age;
public:   
    SampleTest(char *name1, int age) {
        int l = strlen(name1);
        name = new char[l + 1];
        strcpy(this->name, name1);
        this->age = age;
    }
        SampleTest(const SampleTest& s) { //copy constructor 
            int l = strlen(s.name);
            name = new char[l + 1];
            strcpy(this->name, s.name);
            this->age = s.age;
        }
    void displayDetails() {
        cout << "Name is " << this->name << endl;
        cout << "Age is " << this->age << endl;
    }
    void changeName(char* newName) {
        int l = strlen(newName);
        name = new char[l + 1];
        strcpy(this->name, newName);
    }
};
int main() {
    SampleTest s("Test", 10);
    s.displayDetails();
    SampleTest s1(s);
    cout << "From copy constructor" << endl;
    s1.displayDetails();
    s1.changeName("Test1");
    cout << "after changing name s1:";
    s1.displayDetails();
    s.displayDetails();
    cin.get();
    return 0;
}

More Related questions