What is inheritance in C++?
Answer
Inheritance allows a class (derived/child) to inherit members and behaviors from another class (base/parent), enabling code reuse and "is-a" relationships. Syntax: class Animal { public: std::string name; Animal(std::string n) : name(n) {} virtual void speak() const { std::cout << name << " makes a sound\n"; } virtual ~Animal() = default; // Virtual destructor! }; class Dog : public Animal { public: Dog(std::string n) : Animal(n) {} void speak() const override { std::cout << name << " says: Woof!\n"; } void fetch() { std::cout << name << " fetches the ball!\n"; } };. Access inheritance types: public — public/protected base members keep their access; protected — public base members become protected; private — all base members become private. Public is standard. Calling base class methods: Dog::speak() { Animal::speak(); // Explicit base call std::cout << "Also barks\n"; }. Constructor chaining: derived class must call base constructor via initializer list: Dog(std::string n, std::string breed) : Animal(n), breed(breed) {}. Virtual destructor — critical: if you delete a derived object through a base pointer, the base destructor MUST be virtual or only the base destructor runs (resource leak/UB): Animal* a = new Dog("Rex"); delete a; // Calls ~Dog then ~Animal only if virtual. Multiple inheritance: class FlyingFish : public Fish, public Bird {} — C++ supports it. Diamond problem solved with virtual base classes.
Previous
What is function overloading in C++?
Next
What are virtual functions and polymorphism in C++?