OOP Interview Questions (C++)
This section covers common Object-Oriented Programming interview questions, specifically tailored for C++ developers.
Core Principles
1. What are the four pillars of OOP?
- Encapsulation: Binding data and the functions that manipulate them into a single unit (class), and hiding the internal state (using access specifiers).
- Abstraction: Hiding complex implementation details and exposing only the essential features to the user (e.g., through interfaces or abstract classes).
- Inheritance: creating a new class (derived) from an existing class (base) to promote code reuse and establish an "is-a" relationship.
- Polymorphism: The ability of different objects to respond to the same function call in their own way (Compile-time via overloading, Run-time via virtual functions).
2. Why does an empty class have 1 byte of memory in C++? An empty class must have a non-zero size to ensure that two different objects of the same empty class have distinct memory addresses. If the size were zero, an array of empty objects would all share the same address, which violates C++'s object identity rules. Thus, the compiler inserts a dummy byte (1 byte is the minimum addressable unit) to guarantee unique addresses.
3. What is the difference between a struct and a class in C++?
The only difference is default visibility:
- In a
class, members and base classes areprivateby default. - In a
struct, members and base classes arepublicby default.
Advanced C++ OOP
4. What is a virtual function and what is its purpose? A virtual function is a member function proclaimed in the base class and redefined (overridden) by a derived class. It achieves dynamic (run-time) polymorphism, enabling the correct derived class function to be called through a base class pointer or reference.
5. What is the "Rule of Three" (and "Rule of Five")? If a class requires a user-defined destructor, a user-defined copy constructor, or a user-defined copy assignment operator, it almost certainly requires all three. With the advent of C++11 and move semantics, this evolved into the Rule of Five, adding the move constructor and move assignment operator.
6. Explain the concept of RAII. Resource Acquisition Is Initialization (RAII) is a C++ programming technique where resource management (memory, file handles, network sockets) is tied to object lifetime. Resources are acquired in the constructor and released in the destructor.
7. Can constructors or destructors be virtual?
- Constructors cannot be virtual. At the time of construction, the object's dynamic type is not yet fully formed, so the vtable cannot be used to dispatch a virtual call.
- Destructors should be virtual, especially in base classes designed for polymorphism. A virtual destructor ensures that when a derived object is deleted via a base class pointer, both the derived and base destructors are properly invoked, preventing memory leaks.