
class Bear : public ZooAnimal { ... };
is extended to support a comma-separated list of base classes. For example:
class Panda : public Bear, public Endangered { ... };
Each listed base class must also specify its access level, one of public, protected, or private. As with single inheritance, a base class under multiple inheritance can be listed only if its definition has already been seen.
print(), therefore, is resolved only using name resolution on the name print rather than using overload resolution based on the actual argument types. #include <iostream>
class ZooAnimal {
public:
void gender(){
std::cout << "ZooAnimal::gender()\n";
}
virtual void color() = 0;
};
class Endangered {
public:
void landAnimals() {
std::cout << "Endangered::landAnimals()\n";
}
virtual void highlight() = 0;
};
class Bear : public ZooAnimal {
public:
virtual void color(){
std::cout << "Bear::color()\n";
}
void hungry(){
std::cout << "Bear::hungry()\n";
}
};
class Panda : public Bear, public Endangered {
public:
void color() override {
std::cout << "Panda::color()\n";
}
void highlight() override {
std::cout << "Panda::highlight()\n";
}
};
int main() {
ZooAnimal* p = new Panda;
p->gender(); // ZooAnimal::gender()
p->color(); // Panda::color()
//p->highlight(); // Error
//p->hungry(); // Error
Bear* q = new Panda;
q->gender(); // ZooAnimal::gender()
q->color(); // Panda::color()
q->hungry(); // Bear::hungry()
Endangered* r = new Panda;
r->highlight(); // Panda::highlight()
r->landAnimals(); // Endangered::landAnimals()
Panda s;
s.color(); // Panda::color()
s.highlight(); // Panda::highlight()
s.hungry(); // Bear::hungry()
s.landAnimals(); // Endangered::landAnimals()
s.gender(); // ZooAnimal::gender()
}
When a Bear or ZooAnimal pointer or reference is initialized with or assigned the address of a Panda class object, both the Panda-specific and Endangered portions of the Panda interface are no longer accessible. Similarly, when an Endangered pointer or reference is initialized with or assigned the address of a Panda class object, both the Panda-specific and Bear portions of the Panda interface are no longer accessible.