Jump to content

constructor

Featured Replies

what is the copy constructor? how is it different from default constructor?

(in C++)

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

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...
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

Archived

This topic is now archived and is closed to further replies.

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.

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.