Copy constructor and new
Consider the following code snippet:
Will the copy constructor for List_Node be activated when new is called? I have written a program that uses code similar to this, and although it seems to work, I have never seen copy constructors used like this in any books or online articles.
ptr = new List_Node(node);
No, the copy constructor is not called. The constructor is, though.
Had ptr not been a pointer, then yes, the copy constructor would have been called.
That's what I thought, but the thing is that I don't have a List_Node constructor that takes a List_Node object as an argument, so why does the code above work at all?
The only constructor that matches the above call is the copy constructor, so surely it must be called then?
List_Node(const List_Node& ref); // Copy constructor
A class that takes a (const) reference to itself as argument is called a copy constructor.
But you're dealing with pointers, which is a native type, hence no copy constructors are called.
You are creating a new List_Node object, though, which is why the List_Node() constructor is called (not copy constructor).
But shouldn't the compiler complain that I'm calling the constructor with an argument that it's not declared for? And it doesn't explain why the constructor does everything my copy constructor is supposed to be doing when there's no such code in the constructor.
I'm guessing g++ is doing something strange so that the program works, but at least I now know the code is not portable.
And just to elaborate on what Elysia said, references, pointers, and POD's don't really have constructors (there are some cases where C++ pretends that they do, but that's beside the point here).
Ok, I misunderstood your question. If you defined a copy constructor, then yes, that is being called when the object is created. If not, then the default (eg: compiler generated) copy constructor is being called.
Originally Posted by Memloop
What are you talking about. Naturally the copy constructor is called:
And it works because the compiler automatically generates a default copy constructor for classes if you don't do so (default being shallow member-wise copy).
List_Node node; //default constructor
ptr = new List_Node(node); //copy constructor
Thanks for clearing that up, but I find it strange that I have never seen a copy constructor used in combination with new in any C++ litterature or in online tutorials.
You can use any constructor in combination with new:
X* p = new X("Hello world", 3.14, 42);
Eh, I missed that it isn't actually just creating a new object, but making a copy of an existing object.
Of course the copy constructor will be called then...
Sorry about the confusion.