Jump to content

constructor


chitrangda

Recommended Posts

Link to comment
Share on other sites

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

Link to comment
Share on other sites

  • 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

Link to comment
Share on other sites

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.