What is inheritance in C++?
Why Interviewers Ask This
This is a classic screening question for C++ roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.
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.
Pro Tip
Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a C++ codebase.
Previous
What is function overloading in C++?
Next
What are virtual functions and polymorphism in C++?