Hello everyone,
I wanted help on the exact use of copy constructors as I still havent got the idea of how they are used. If possible also I would like some info about them.
Also I wished some guidance on which books to refer after studying linked lists in C. Any suggestions would be welcome.
Thanks,
comwizz. :)

Here's my understanding of copy constructors.

Copy constructors create a new object of the type of the class it is in from an already existing object of that type. Routinely, the data in the object passed is used to populate the data members in the new object so the new object is an exact copy of the original. If the objects contain data within pointers, you may or may not want to copy the address of the data as opposed to the data itself.

Routinely, the assignment operator does the same thing as the copy constructor except it copies data from one existing object into another existing object, so no new object is created. In addition, it doesn't make a lot of sense to copy an object into itself, though there isn't any reason you couldn't. The code for an assignment operator is frequently slightly different from the copy constructor in that it checks the two objects for identity before entering the working section of the code.

If you want to construct a new object using dynamic memory from an object in static memory then you need to use the new operator. The new operator routinely uses the default constructor, though I don't know if it can use the copy constructor or not. If not, then you create the new object and use the assignment operator to copy the data from the object in static memory into the object in dynamic memory. IF you can use the copy constructor with the new operator, then you would be able to accomplish the task in one step.

The copy constructor can be called by the compiler without your explicit instructions, so all classes/structs in C++ need a copy constructor. If you don't create one explicitly, then the compiler will create one for you. The default copy constructor copies the address in a pointer rather than the data at the address in the pointer. If that's what you want fine. If not, then you need to write a copy constructor for your class.

1.IF you can use the copy constructor with the new operator, then you would be able to accomplish the task in one step.

2.The default copy constructor copies the address in a pointer rather than the data at the address in the pointer. If that's what you want fine. If not, then you need to write a copy constructor for your class.

I would like an example for using copy constructor with new operator.

Also if the address in a pointer is copied then it indirectly serves our purpose as the pointer can be dereferenced to get the value or data.
Please reply.
Your reply was of great help.
Thanks,
comwizz.

Thanks for the help . The tutorial is just about perfect.
thanks,
comwizz

This article has been dead for over six months. Start a new discussion instead.