简体   繁体   中英

C++ Inheritance: Calling Parent Class Constructor

I'm hitting my head against the wall trying to remember how to deal with inheritance. Lets say we have a parent/base class called Fruits and child/derived class called Apples. Apples is only different from Fruits in that it has one extra variable, called number. How would we implement it so that Apples by default always calls the parent class constructor, with the values "Apples" (the name) and SNACK (the type)?

Fruits would be implemented as such (

Fruits::Fruits(string name, KIND type): myName(name), myKind(type)
{}

How would Apples be implemented, so that if Apples is called as Apples() it defaults name to "Apples" and type to SNACK, with number to 5? Is this correct?

Apples::Apples() : Fruits("Apple", SNACK)
{
    number = 5;
}
 Apples::Apples(int num)  : FoodItem("Pancakes", BREAKFAST )
{

}

This way is correct:

Apples::Apples() : Fruits("Apple", BREAKFAST)
{
    number = 5;
}

but this way would be better as it more readable and consistent:

Apples::Apples() : Fruits("Apple", BREAKFAST), number( 5 )
{
}

I would try these:

// Default value for number
Apples::Apples() : Fruits("Apple", SNACK), number(5)
{
}

// Caller specified value for number
Apples::Apples(int num)  : FoodItem("Pancakes", BREAKFAST), number(num)
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM