Yes, indeed.
The argument "model" is assigned to the member model. |
That is the point. Assigned. The this->model has already been constructed and does contain some value. The assignment changes the value of an existing object.
Technical meaning:
* Initialization. Object starts existence with specified value.
* Assignment. The current value of an object is replaced with a new value.
Logical view:
* After the constructor of a Laptop has completed, all the member variables of the Laptop have the the values that you want them to have, so your Laptop does not have undefined state. Logically initialized.
If there is something "wrong", it is all the unnecessary work that your constructor does.
The question was:
How can I call the Battery constructor (the one which takes 2 arguments) |
The answer is: use initialization list
1 2 3 4
|
Laptop::Laptop( string battery, double battery_life )
: baterry( battery, battery_life ) // calls constructor to create the baterry object. This is initialization
{
}
|
If you don't write initialization list, then the compiler will create it with default constructors:
1 2 3 4
|
Laptop::Laptop( string battery, double battery_life )
: baterry() // calls constructor to create the baterry. This is initialization
{
}
|
But you want to use those parameters, yes?
1 2 3 4 5 6
|
Laptop::Laptop( string battery, double battery_life )
: baterry() // calls constructor to create the baterry. This is initialization
{
Battery temp( battery, battery_life ); // construct a temporary object
baterry = temp; // this is copy assignment
} // the destructor of temp is called here
|
Compared to the initializer list version, there are additional calls to Battery default constructor, copy assignment, and destructor.
Lets try something different:
1 2 3 4 5
|
class Foo {
const int bar;
public:
Foo( int bar );
};
|
Implement that constructor. The constructor's parameter value must be stored in the class' member bar.