Jump to content

Recommended Posts

Posted
A copy constructor is a special constructor that initializes a new object from an existing object.

 

If you have anymore questions, I'd advise having a look at Learn C++(Chapter 9.11), or alternatively the Learn C++ forums; it does an excellent job of explaining not only this.

 

Cheers,

 

Gabe

Posted
Posted

The default constructor takes no arguments (or rather, all arguments are optional). The copy constructor takes one argument, a reference to an instance of the same class being constructed. The intent is that the newly created item will be a "copy" of the supplied item.

 

If you do not declare a copy constructor for a class, you get one au gratis. This freebie copy constructor simply copies the memory contents from the supplied instance to the newly created instance. This might well be exactly what you want -- except when it isn't.

 

For example, suppose one of the member data elements of your class is a pointer to an instance of some other class. Being a good programmer, you have written a destructor for the class that deletes this pointer. The freebie copy constructor simply copies the pointer rather than creating a copy of the pointed-to object. Now suppose this copied object goes out of scope but the original remains in scope. The destructor will be called for the copied object and thus the pointer will be deleted. You now have a *big* problem: The original instance suddenly contains an invalid pointer.

 

The solution: If you need to write a destructor for some class, you probably also need to write a copy constructor (and a copy assignment operator, operator=) as well. In fact, if you need to write any one of these three key methods you probably need to write all three of them. (This is "Law of The Big Three".)

  • 2 weeks later...
Posted
For example, suppose one of the member data elements of your class is a pointer to an instance of some other class.

 

Solution: Avoid pointers, and when you absolutely must use them, use smart pointers, or at the very least auto_ptr

 

Also: C++ hurts my head

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.