Explain Encapsulation, Inheritance, and Polymorphism in C++
Company: Point72
Role: Data Scientist
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Technical Screen
# Explain Encapsulation, Inheritance, and Polymorphism in C++
Explain encapsulation, inheritance, and polymorphism in C++ by designing a small hierarchy with one stable public interface and at least two implementations. Discuss access control, object lifetime, virtual dispatch, substitution, composition versus inheritance, and the pitfalls of copying or destroying objects through base types.
### Constraints & Assumptions
- Use resource-safe C++ ownership rather than raw owning pointers.
- If objects are deleted through a base pointer, address the base destructor explicitly.
- Separate compile-time overloading or templates from runtime virtual dispatch.
- Do not expose internal representation merely to make tests convenient.
### Clarifying Questions to Ask
- Is the relationship truly an is-a relationship or would composition model it better?
- Must derived objects be copied, moved, or owned polymorphically?
- Which invariants should only the class itself be able to mutate?
```hint Protect invariants
Encapsulation is about controlling valid state transitions, not simply marking every field private.
```
```hint Follow ownership
A polymorphic interface needs an explicit lifetime plan, commonly smart pointers and a virtual destructor.
```
### What a Strong Answer Covers
- Concrete definitions connected to a coherent class example.
- Correct virtual destructor and object-slicing discussion.
- Liskov-style substitutability and why inheritance can break invariants.
- Trade-offs among virtual interfaces, templates, variants, and composition.
### Follow-up Questions
- When would a tagged variant be preferable to a virtual hierarchy?
- How can a derived method violate substitutability even when its signature matches?
Quick Answer: Explain encapsulation, inheritance, and polymorphism in C++ by designing a small hierarchy with one stable public interface and at least two implementations. Make the API or object boundaries explicit, then cover invariants, edge cases, testing strategy, and operational trade-offs.