Inheritance & Polymorphism¶
Inheritance allows you to create new classes based on existing ones, promoting code reuse. Polymorphism allows you to treat objects of different types uniformly.
Inheritance Basics¶
A derived class inherits members from a base class.
Access Control in Inheritance¶
publicinheritance:publicmembers staypublic,protectedstayprotected. (Most common)protectedinheritance:publicandprotectedbecomeprotected.privateinheritance: All inherited members becomeprivate. (Implementation inheritance)
Polymorphism & Virtual Functions¶
Polymorphism allows a function to behave differently based on the object it is called on. This is achieved using virtual functions.
Abstract Classes & Pure Virtual Functions¶
An abstract class defines an interface but not necessarily an implementation. It cannot be instantiated directly.
A function becomes pure virtual by assigning = 0 to it.
Virtual Destructors¶
Crucial Rule: If a class is intended to be used as a base class, its destructor must be virtual.
If not, deleting a derived object through a base pointer results in undefined behavior (usually a resource leak because the derived destructor is not called).
The final Keyword¶
You can prevent a class from being inherited or a function from being overridden.