Inheritance models is-a relationships: class Dog : public Animal. The derived class inherits members and can extend or override behavior.
Basic inheritance
class Animal {
public:
void speak() const { std::cout << "...\n"; }
};
class Dog : public Animal {
public:
void speak() const { std::cout << "woof\n"; }
};
Without virtual, overriding is static—use base references carefully to avoid slicing when copying by value.
Important interview questions and answers
- Q: public vs protected inheritance?
A: Controls how base members appear in the derived interface—publicis-a semantics for users. - Q: Object slicing?
A: Assigning derived to base by value slices off derived data—use references or pointers.
Self-check
- What does protected: access allow?
- When does slicing happen?
Pitfall: Object slicing when assigning derived to base by value—use references, pointers, or virtual interfaces.
Interview prep
- Object slicing?
Copying a derived object into a base object by value slices off derived data—use references or pointers.
- protected access?
Visible to derived classes but not typically to unrelated code.