Inheritance allows a derived (child) class to inherit attributes and methods from a base (parent) class. This fosters code reuse and establishes logical taxonomies.
virtual Base Classes#include <iostream>
class Device {
public:
int powerRating = 100;
};
// Virtual inheritance ensures only ONE instance of Device is shared
class Printer : virtual public Device {};
class Scanner : virtual public Device {};
class Copier : public Printer, public Scanner {
// Contains exactly one shared 'powerRating' instance!
};
int main() {
Copier c;
std::cout << "Copier Power: " << c.powerRating << "W\n"; // Zero ambiguity!
return 0;
}
Boost your C++ proficiency by studying these closely connected core modules:
Enabling runtime polymorphism in derived classes.
Public vs protected inheritance rules.
Understanding the 'is-a' relationship.