Using inheritance in C++ effectively requires understanding the differences between public, private, and protected inheritance. This knowledge allows developers to control access to the base class members and to design systems that are maintainable and secure.
When a class is publicly inherited, the public and protected members of the base class remain accessible in the derived class. Public inheritance is often referred to as "is-a" relationship.
In private inheritance, the public and protected members of the base class become private members of the derived class. This means they are not accessible outside of the derived class. Private inheritance is used to indicate a "implemented-in-terms-of" relationship.
Protected inheritance makes the public and protected members of the base class accessible only to the derived class and its subclasses. This is somewhat of a niche use case for specialized relationships.
class Base {
public:
void publicMethod() {}
protected:
void protectedMethod() {}
private:
void privateMethod() {}
};
class DerivedPublic : public Base {
public:
void useBaseMethods() {
publicMethod(); // Accessible
protectedMethod(); // Accessible
// privateMethod(); // Not accessible
}
};
class DerivedPrivate : private Base {
public:
void useBaseMethods() {
publicMethod(); // Accessible
protectedMethod(); // Accessible
// privateMethod(); // Not accessible
}
};
class DerivedProtected : protected Base {
public:
void useBaseMethods() {
publicMethod(); // Accessible
protectedMethod(); // Accessible
// privateMethod(); // Not accessible
}
};
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?