In Sybex book, Under constructor overloading it says
This attempt does compile. It doesn't do what we want, though. When the constructor
with one parameter is called, it creates an object with the default weight and color. It then
constructs a different object with the desired weight and color and ignores the new object.
That's not what we want. We want weight and color set on the object we are trying to
instantiate in the first place.
I have a confusion in understanding the concept here. I believe above quote is in reference with the code attached. If I am right then my confusion is in single parameter constructor.Here, we
are passing only weight parameter then how is an object is created with default weight and color ? and also when they say new object is ignored do they mean first created object by single parameter constructor ?
I doubt that code I am referring is wrong or my understanding about objects. This might seem silly doubt but it would help my understanding.
From the point of view of the object being created using the 'weight' constructor, the constructor may as well be:
As the extra Hamster object created using 'new' is not stored anywhere.
As you can see, the 'weight' parameter is not being used for this Hamster, so the values for the attributes will stay at their default.
To take the whole constructor, as in your post, if I create a Hamster as follows:
I would end up with a Hamster with default values (as above), and while it was creating that Hamster, it would create an extra Hamster inside the constructor, whose reference is never retained and so will be eligible for garbage collection straight away.