Next, we will modify the animal class constructor and add two parameters, height and weight, to indicate the height and weight of the animals respectively. The code is shown in example 2-13.
Example 2-13
# Include <iostream. h>
Class animal
{
Public:
Animal (INT height, int weight)
{
Cout <"animal construct" <Endl;
}
~ Animal ()
{
Cout <"Animal destruct" <Endl;
}
Void eat ()
{
Cout <"Animal eat" <Endl;
}
Void sleep ()
{
Cout <"Animal sleep" <Endl;
}
Void breathe ()
{
Cout <"Animal breathe" <Endl;
}
};
Class fish: Public animal
{
Public:
Fish ()
{
Cout <"Fish construct" <Endl;
}
~ Fish ()
{
Cout <"Fish destruct" <Endl;
}
};
Void main ()
{
Fish FH;
}
When we compile this program, the following error occurs:
How does this error occur? When constructing the fish object FH, it needs to first construct the animal Class Object and call the default constructor of the animal class (that is, the constructor without parameters ), in our program, the animal class has only one constructor with parameters. during compilation, an error occurs because the default constructor of the animal class cannot be found.
Therefore, when constructing an object of the fish class (when calling the constructor of the fish class), if you want to call a constructor with parameters of the animal class, how do we pass parameters to the constructor of the parent class in the subclass? You can use the method shown in Figure 2-14 to explicitly call the constructors with parameters of the parent class when constructing child classes.
Example 2-14
# Include <iostream. h>
Class animal
{
Public:
Animal (INT height, int weight)
{
Cout <"animal construct" <Endl;
}
...
};
Class fish: Public animal
{
Public:
Fish (): Animal (1, 400,300)
{
Cout <"Fish construct" <Endl;
}
...
};
Void main ()
{
Fish FH;
}
Note the code in bold in the program. Add a colon (:) after the constructor of the fish class, and then add the constructor with parameters of the parent class. In this way, when the constructor of the subclass is called, the system will call the constructor with parameters of the parent class to construct the object. This initialization method is also often used to initialize a constant (const) member in the class, as shown in the following code:
Class Point
{
Public:
Point (): x (0), y (0)
PRIVATE:
Const int X;
Const int y;
};
Of course, common member variables in the class can also be initialized in this way. However, this is unnecessary.